I need a way to run an update function of my own in the main thread. I couldn't find a signal that would tick me every time the main loop runs.
Am I doing this wrong ? Is it a Qt thing to force user code to run in threads if we want to run something in a loop?
Adding a Widgetmainloop() tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until you close the window where you called the method.
Import the required libraries and create an instance of tkinter frame. Set the size of the frame using win. geometry method. Next, create a user-defined function "infinite_loop" which will call itself recursively and print a statement on the window.
Generally, in programming languages, to stop a continuous while loop, we use a break statement. However, in Tkinter, in place of the while loop, we use after() to run the defined function in a loop. To break the continuous loop, use a global Boolean variable which can be updated to change the running state of the loop.
Python Tkinter Mainloop Update Update() method in mainloop in Python Tkinter is used to show the updated screen. It reflects the changes when an event occurs.
QTimer::singleShot(0, []{/* your code here */});
That's about it, really. Using a 0ms timer means your code will run on the next event loop iteration. If you want to make sure the code won't run if a certain object doesn't exist anymore, provide a context object:
QTimer::singleShot(0, contextObj, []{/* your code here */});
This is well documented.
I used a lambda here just for the example. Obviously you can provide a slot function instead if the code is long.
If you want your code to be executed repeatedly on every event loop iteration instead of just once, then use a normal QTimer that is not in single-shot mode:
auto timer = new QTimer(parent);
connect(timer, &QTimer::timeout, contextObj, []{/* your code here */});
timer->start();
(Note: the interval is 0ms by default if you don't set it, so QTimer::timeout()
is emitted every time events have finished processing.)
Here's where this behavior is documented.
And it goes without saying that if the code that is executed takes too long to complete, your GUI is going to freeze during execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With