首页 > 解决方案 > 如何在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 窗口永远不会打开,而不是更改显示的文本。我知道我一定是在看一些简单的东西,但我似乎无法弄清楚是什么。提前感谢您的帮助!

标签: pythonpython-3.xtkinter

解决方案


由于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

推荐阅读