我试图在 tkinter 窗口中每隔几秒钟从字典中显示一个随机短语。我可以通过在 tkinter 的文本框中运行一个变量来显示该短语,但我似乎无法让该短语在所需的时间间隔内更改。到目前为止,这是我拥有的代码。import timeimport sysimport randomimport tkinter as tkfrom tkinter import *""" DICTIONARY PHRASES """phrases = ["Phrase1", "Phrase2", "Phrase3"]def phraserefresh(): while True: phrase_print = random.choice(phrases) time.sleep(1) return phrase_printphrase = phraserefresh()# Root is the name of the Tkinter Window. This is important to remember.root=tk.Tk()# Sets background color to blackroot.configure(bg="black")# Removes the window bar at the top creating a truely fullscreenroot.wm_attributes('-fullscreen','true')tk.Button(root, text="Quit", bg="black", fg="black", command=lambda root=root:quit(root)).pack()e = Label(root, text=phrase, fg="white", bg="black", font=("helvetica", 28))e.pack()root.mainloop()运行此代码的结果是 tkinter 窗口永远不会打开,而不是更改显示的文本。我知道我一定是在看一些简单的东西,但我似乎无法弄清楚是什么。提前感谢您的帮助!
1 回答
哆啦的时光机
TA贡献1779条经验 获得超6个赞
由于while True循环,此函数永远不会返回:
def phraserefresh():
while True:
phrase_print = random.choice(phrases)
time.sleep(1)
return phrase_print # This line is never reached
您可以使用该after()方法设置重复延迟并更改标签文本。
def phrase_refresh():
new_phrase = random.choice(phrases)
e.configure(text=new_phrase) # e is your label
root.after(1000, phrase_refresh) # Delay measured in milliseconds
添加回答
举报
0/150
提交
取消