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
399 views
in Technique[技术] by (71.8m points)

python - How do I create an automatically updating GUI using Tkinter?

from Tkinter import *
import time
#Tkinter stuff

class App(object):
    def __init__(self):
        self.root = Tk()

        self.labeltitle = Label(root, text="",  fg="black", font="Helvetica 40 underline bold")
        self.labeltitle.pack()

        self.labelstep = Label(root, text="",  fg="black", font="Helvetica 30 bold")
        self.labelstep.pack()

        self.labeldesc = Label(root, text="",  fg="black", font="Helvetica 30 bold")
        self.labeldesc.pack()

        self.labeltime = Label(root, text="",  fg="black", font="Helvetica 70")
        self.labeltime.pack()

        self.labelweight = Label(root, text="",  fg="black", font="Helvetica 25")
        self.labelweight.pack()

        self.labelspeed = Label(root, text="",  fg="black", font="Helvetica 20")
        self.labelspeed.pack()

        self.labeltemp = Label(root, text="", fg="black", font="Helvetica 20")
        self.labeltemp.pack()

        self.button = Button(root, text='Close recipe', width=25, command=root.destroy)
        self.button.pack()

    def Update(self, label, change):
        label.config(text=str(change))

def main():
    app = App()
    app.mainloop()

if __name__ == "__main__":
    main()

I'm trying to create a recipe display which will show the step, instructions, weight and other variables on a screen in a Tkinter GUI.

However, I do not know how to update the GUI to change with each new step of the recipe, as the content has to be dynamically updated based on user input (taken from a server). How can I achieve updating of the GUI's other elements based on the change in steps?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use after() to run function after (for example) 1000 miliseconds (1 second) to do something and update text on labels. This function can run itself after 1000 miliseconds again (and again).

It is example with current time

from Tkinter import *
import datetime

root = Tk()

lab = Label(root)
lab.pack()

def clock():
    time = datetime.datetime.now().strftime("Time: %H:%M:%S")
    lab.config(text=time)
    #lab['text'] = time
    root.after(1000, clock) # run itself again after 1000 ms

# run first time
clock()

root.mainloop()

BTW: you could use StringVar as sundar nataraj Сундар suggested


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

...