Tkinter Multiple Operations
Solution 1:
Short answer, you can't do exactly what you want. Tkinter is single threaded -- when you call sleep(2)
it does exactly what you ask it to: it sleeps.
If your goal is to execute something every 2 seconds as long as a boolean flag is set to True, you can use after to schedule a job to run in the future. If that job also uses after to (re)schedule itself, you've effectively created an infinite loop where the actual looping mechanism is the event loop itself.
I've taken your code and made some slight modifications to show you how to execute something continuously until a flag tells it to stop. I took the liberty of renaming "toggle" to "running" to make it a little easier to understand. I also use just a single method to both turn on and turn off the execution.
from Tkinter import *
from time import sleep
classApp:
def__init__(self, master):
self.master = master
self.running = False
frame = Frame(master)
frame.pack()
self.exeButton = Button(frame, text="Execute", fg="blue",
command=lambda: self.execute(True))
self.exeButton.pack(side=LEFT)
self.tOffButton = Button(frame, text="Toggle Off",
command=lambda: self.execute(False))
self.tOffButton.pack(side=LEFT)
defexecute(self, running=None):
if running isnotNone:
self.running = running
if self.running:
print"hi there, everyone!"
self.master.after(2000, self.execute)
root = Tk()
app = App(root)
root.mainloop()
Post a Comment for "Tkinter Multiple Operations"