Why on click of button it doesn't change text and color? #1584
-
On click of button it changes text and color, after another 10 seconds it changes text and color again but it doesn't change text and color in the first place. What is the reason? The code is as follows,
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The explanation for this requires a little bit of understanding of how GUI apps work. A GUI app is, at the code, essentially the following code:
That is - it is in a constant loop redrawing, then handling events (things like mouse clicks, keyboard presses, etc). While the GUI is redrawing, it's not handling events; and when it's handling events, it's not redrawing. Your You'll also likely notice that when you press the button, the app "beachballs" - it shows a the "hourglass" or "rainbow pinwheel" icon, indicating the app has locked up. That's the operating system telling you that the app hasn't redrawn for a while. The fix - don't use a blocking event handler, Use an asynchronous handler instead:
By making the handler asynchronous, you're telling Toga that while the method is sleeping, it can give control back to the GUI to redraw the app. That also means the text and style changes can be applied, because the GUI gets a chance to redraw. As a general rule, you can't do anything in an event handler that takes a long time (anything longer than >0.1s is likely too long). You need to either use asynchronous handlers, so that the handler will share time with the app's redraw, or run the "heavy work" in a background thread. However, keep in mind that if the "work" includes GUI updates, you can't make those GUI updates from the thread. GUI updates can only happen on the GUI thread. If you want to update a GUI element from a worker thread, you need to post those updates to the main thread by creating an asyncio.Task. |
Beta Was this translation helpful? Give feedback.
The explanation for this requires a little bit of understanding of how GUI apps work.
A GUI app is, at the code, essentially the following code:
That is - it is in a constant loop redrawing, then handling events (things like mouse clicks, keyboard presses, etc). While the GUI is redrawing, it's not handling events; and when it's handling events, it's not redrawing.
Your
start()
method is an event handler; so when you invoke it, that code will be executed, one line after another. However -time.sleep()
is a blocking method. While the code is sleeping in that call, the app isn't doing anything else - including redrawing itself. You've change…