How to run an infinite loop on Menu?
Thomas Jollans
tjol at tjol.eu
Mon Dec 3 04:03:40 EST 2018
On 03/12/2018 08:58, huey.y.jiang at gmail.com wrote:
> Hi Folks,
>
> I need to run an infinite loop on a Menu button, like this:
>
> from Tkinter import *
>
> def run_job():
> i = 0
> while 1:
> i = i + 1
> if i > 100:
> break
> .......
>
> root = Tk()
> menu = Menu(root)
> root.config(menu=menu)
> filemenu = Menu(menu)
> menu.add_cascade(label="Jobs", menu=filemenu)
> filemenu.add_command(label="Run", command=run_job)
> mainloop()
>
>
> In fact, the def run_job has more things to do. But, it is an infinite loop in essence. It works. However, when the def run_job is running, the menu will be hang there. I have no way to stop it. Even if I raise it with Key-Interupt, the thing was the same: the infinite loop cannot be stopped nicely. The only way was to wait until the Python interpreter notice the problem, and popped out an error message, then I can kill the running program.
Basic rule of thumb for GUI programming: never block the main (GUI)
thread, i.e. never run any long-running task in the main thread.
If you want to start a long-running task from a GUI event, start a
worker thread; from there, you could then perhaps update a progress bar
in your loop. If you want to be able to stop the task from the GUI,
you'll want something like a "stop the task ASAP please" flag/variable
set by the stop button that the loop periodically checks.
>
> Can anybody tell me how to handle this? I wish when variable i reached 100, the run_job will be end, and the Menu "Run" will be free.
>
> Thanks in advance.
>
More information about the Python-list
mailing list