Tkinter multiple operations

2019-07-23 06:19发布

My question is similar to this: Python TKinter multiple operations. However, The answer provided does not help me since it points to an article with a list of possible functions to use. I want to see an actual implementation of the solution please.

My question: I have two buttons on a frame. one button calls the 'execute' function as long as the toggle variable is set to true. The 2nd button sets the toggle value to False. I want the 'execute' function to keep going once i press the execute button but stop when i press the 2nd (toggle false) button. However, the frame gets stuck once i press 'execute'. I understand its because of callbacks. How can i fix this? Heres my sample code:

from Tkinter import *
from time import sleep

class App:

    def __init__(self, master):

        self.toggle = False
        frame = Frame(master)
        frame.pack()

        self.exeButton = Button(frame, text="Execute", fg="blue", command=self.execute)
        self.exeButton.pack(side=LEFT)

        self.tOffButton = Button(frame, text="Toggle Off", command=self.toggleOff)
        self.tOffButton.pack(side=LEFT)

    def execute(self):
        self.toggle = True
        while(self.toggle):
            print "hi there, everyone!"
            sleep(2)

    def toggleOff(self):
    self.toggle = False

root = Tk()
app = App(root)
root.mainloop()

1条回答
闹够了就滚
2楼-- · 2019-07-23 07:09

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

class App:

    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)

    def execute(self, running=None):
        if running is not None:
            self.running = running
        if self.running:
            print "hi there, everyone!"
            self.master.after(2000, self.execute)

root = Tk()
app = App(root)
root.mainloop()
查看更多
登录 后发表回答