Python 如何使用 Tkinter 创建自动更新的 GUI?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24849265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:20:01  来源:igfitidea点击:

How do I create an automatically updating GUI using Tkinter?

pythonuser-interfacedynamictkinter

提问by RainingEveryday

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.

我正在尝试创建一个配方显示,它将在 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?

但是,我不知道如何更新 GUI 以随着配方的每个新步骤进行更改,因为内容必须根据用户输入(从服务器获取)动态更新。如何根据步骤的变化来更新 GUI 的其他元素?

采纳答案by furas

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).

您可以使用after()在(例如)1000 毫秒(1 秒)后运行函数来执行某些操作并更新标签上的文本。此函数可以在 1000 毫秒后再次(又一次)自行运行。

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 StringVaras sundar nataraj Сундарsuggested

顺便说一句:你可以StringVarsundar nataraj Сундар建议的那样使用

回答by sundar nataraj

if you want to change label dynamically

如果您想动态更改标签

self.dynamiclabel=StringVar()
self.labeltitle = Label(root, text=self.dynamiclabel,  fg="black", font="Helvetica 40 underline bold")
self.dyanamiclabel.set("this label updates upon change")
self.labeltitle.pack()

when ever you get new value then just use .set()

当您获得新价值时,只需使用 .set()

self.dyanamiclabel.set("Hurrray! i got changed")

this apply to all the labels.To know more read this docs

这适用于所有标签。要了解更多信息,请阅读此文档

回答by xing cao

I added a process bar in my window, and change its value according to randint for every 1 second using the update function:

我在窗口中添加了一个进程栏,并使用 update 函数每 1 秒根据 randint 更改其值:

from random import randint
def update():
    mpb["value"] = randint(0, 100) # take process bar for example
    window.after(1000, update)
update()
window.mainloop()

回答by Manish Gupta

I wrote an example with Python 3.7

我用 Python 3.7 写了一个例子

from tkinter import *

def firstFrame(window):
    global first_frame
    first_frame = Frame(window)
    first_frame.place(in_=window, anchor="c", relx=.5, rely=.5)
    Label(first_frame, text="ATTENTION !").grid(row=1,column=1,columnspan=3)


def secondFrame(window):
    global second_frame
    second_frame= Frame(window, highlightbackground=color_green, highlightcolor=color_green, highlightthickness=3)
    second_frame.place(in_=window, anchor="c", relx=.5, rely=.5)
    Label(second_frame, text="This is second frame.").grid(row=1, column=1, columnspan=3, padx=25, pady=(15, 0))


window = Tk()
window.title('Some Title')
window.attributes("-fullscreen", False)
window.resizable(width=True, height=True)
window.geometry('300x200')


firstFrame(window)
secondFrame(window)
first_frame.tkraise()
window.after(5000, lambda: first_frame.destroy()) # you can try different things here
window.mainloop()

回答by Matěj Mudra

If you are using labels, then you can use this:

如果您使用标签,那么您可以使用这个:

label = tk.Label(self.frame, bg="green", text="something")
label.place(rely=0, relx=0.05, relwidth=0.9, relheight=0.15)

refresh = tk.Button(frame, bg="white", text="Refreshbutton",command=change_text) 
refresh.pack(rely=0, relx=0.05, relwidth=0.9, relheight=0.15)

def change_text()
   label["text"] = "something else"

Works fine for me, but it is dependent on the need of a button press.

对我来说很好用,但这取决于是否需要按下按钮。