Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

python - Run an infinite loop in the backgroung in Tkinter

I would like the code to run in the background and to update my GUI periodically. How can I accomplish this?

For example, suppose I want to execute something like this in the background of the GUI code you can see below:

x = 0

while True:
   print(x)
   x = x + 1
   time.sleep(1)

This is the GUI code:

class GUIFramework(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.master.title("Volume Monitor")
        self.grid(padx=10, pady=10,sticky=N+S+E+W)
        self.CreateWidgets()

    def CreateWidgets(self):
        textOne = Entry(self, width=2)
        textOne.grid(row=1, column=0)

        listbox = Listbox(self,relief=SUNKEN)
        listbox.grid(row=5,rowspan=2,column=0,columnspan=4,sticky=N+W+S+E,pady=5)
        listbox.insert(END,"This is an alert message.")

if __name__ == "__main__":
    guiFrame = GUIFramework()
    guiFrame.mainloop()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is a little unclear what your code at the top is supposed to do, however, if you just want to call a function every second (or every the amount of seconds you want), you can use the after method.

So, if you just want to do something with textOne, you'd probably do something like:

...
textOne = Entry(self, width=2)
textOne.x = 0

def increment_textOne():
    textOne.x += 1

    # register "increment_textOne" to be called every 1 sec
    self.after(1000, increment_textOne) 

You could make this function a method of your class (in this case I called it callback), and your code would look like this:

class Foo(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.x = 0
        self.id = self.after(1000, self.callback)

    def callback(self):
        self.x += 1
        print(self.x)
        #You can cancel the call by doing "self.after_cancel(self.id)"
        self.id = self.after(1000, self.callback)  

gui = Foo()
gui.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...