如何有一定的时间后,当Tkinter的标签文本的变化?

问题描述 投票:0回答:2

我设置了一个GUI应用程序,我有一个Tkinter的标签文本改变在time.sleep()计时器的问题。

我已经试过类似

label_text = Label(main_window, text="hello world")
time.sleep(3)
label_text = Label(main_window, text="hello world")

(请注意,我有网系统和Tkinter的窗口设置,我只是不会显示出这里面的所有代码)

# Currently this is not working how I would like it to, but here is the code
main_window = tkinter.Tk()
label_text = Label(main_window, text="hello world")
time.sleep(3)
label_text = Label(main_window, text="hello")
label_text.grid(column=1, row=1)

main_window.mainloop() 

和这个

main_window = tkinter.Tk()
main_window.resizable(False, False)
main_window.geometry("500x900")

text = StringVar()
text.set("hello")
label = Label(main_window, text=text)
label.grid(column=1, row=1)
time.sleep(3)
text.set("anoefn")
main_window.update()

main_window.mainloop()

谢谢!

python tkinter time var
2个回答
1
投票

我想这你想要做什么。您需要使用tk_obj.after获得纯滞后。在睡眠问题的代码延迟主循环的3秒的呼唤。

main_window = tk.Tk()
label_text = tk.Label(main_window, text="hello world")

def on_after():
    label_text.configure( text="hello")

label_text.grid(column=1, row=1)
label_text.after(3000, on_after) # after 3000 ms call on_after

main_window.mainloop()

正如评论说,你可以使用STRINGVAR,链接到标签。然后on_after需要改变,而不是STRINGVAR配置标签。

编辑:为完整带STRINGVAR版本

main_window = tk.Tk()
var=tk.StringVar()
var.set("Hello World")
label_text = tk.Label(main_window, textvariable=var)

def on_after():
    var.set("Hello ") # set the StringVar instead of configuring the label.

label_text.grid(column=1, row=1)
label_text.after(3000, on_after)
main_window.mainloop()

-1
投票

尝试使用STRINGVAR()数据类型

mytext = StringVar()
label_text = Label(main_window, text=mytext)
mytext.set("hello")
#after sometime change the text as required
mytext.set("new text")

希望,这将工作。

© www.soinside.com 2019 - 2024. All rights reserved.