python - 如何在python中每隔几秒钟在tkinter窗口中更改一行文本
问题描述
我试图在 tkinter 窗口中每隔几秒钟从字典中显示一个随机短语。
我可以通过在 tkinter 的文本框中运行一个变量来显示该短语,但我似乎无法让该短语在所需的时间间隔内更改。
到目前为止,这是我拥有的代码。
import time
import sys
import random
import tkinter as tk
from tkinter import *
""" DICTIONARY PHRASES """
phrases = ["Phrase1", "Phrase2", "Phrase3"]
def phraserefresh():
while True:
phrase_print = random.choice(phrases)
time.sleep(1)
return phrase_print
phrase = phraserefresh()
# Root is the name of the Tkinter Window. This is important to remember.
root=tk.Tk()
# Sets background color to black
root.configure(bg="black")
# Removes the window bar at the top creating a truely fullscreen
root.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 窗口永远不会打开,而不是更改显示的文本。我知道我一定是在看一些简单的东西,但我似乎无法弄清楚是什么。提前感谢您的帮助!
解决方案
由于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
推荐阅读
- c# - 构建复杂数据类
- css - 整个站点丢失的容器宽度
- android - Android:是否可以将存储在 Google Cloud Storage 中的图像分享到 Instagram?
- linux - Linux 命令在收到任何输入后运行 shell 脚本
- python - How to sort each row of pandas dataframe and return column index based on sorted values of row
- java - Map.get(数组列表中的项目)
- node.js - Dialogflow 信使推荐
- r - 将新列附加到可以分组的数据中
- json - Azure ARM 模板:DependsOn 条件语句
- android - 滚动时清空卡片视图