首页 > 解决方案 > 如何使用 for 循环更新 Tkinter 标签/画布小部件中的文本?

问题描述

我在更新标签和画布中的文本时遇到问题。更新画布本身的文本很烦人。没找到有用的。

我的项目在这里 - https://github.com/MRDGH2821/Words-Per-Minute-/tree/beta

我想做什么 - 逐字显示段落(中间有一些延迟)

我在编写代码时的想法 - 段落将在文件中。代码将读取段落,提取第一个单词并将它们放入标签小部件中。延迟后,第一个单词将消失,第二个单词将被显示。等等。

代码的实际作用 - 不是显示整个单词,而是显示第一个单词的第一个字母。我使用 for 循环来更新标签小部件中显示的文本,但它不会更新/刷新。

这是代码片段 -

root = tk.Tk()
root.attributes("-fullscreen", True)
root.bind("<F11>", lambda event: root.attributes("-fullscreen", not root.attributes("-fullscreen")))
root.bind("<Escape>", lambda event: root.attributes("-fullscreen", False))
root.bind("<F1>", lambda event: os.exit(0))

w = tk.StringVar()

labelFlash = tk.Label(root, bg='Black', width=root.winfo_screenwidth(), height=root.winfo_screenheight(),
                      anchor="center", text="Sample", fg="White", font="Times " + str(cofg.GetFontSize()), textvariable=w)
labelFlash.pack()
for word in words:
    w.set(word)
    labelFlash.config(text=word)

标签: pythontkintertkinter-canvas

解决方案


import tkinter as tk
root = tk.Tk()
root.attributes("-fullscreen", True)
root.bind("<F11>", lambda event: root.attributes("-fullscreen", not root.attributes("-fullscreen")))
root.bind("<Escape>", lambda event: root.attributes("-fullscreen", False))
root.bind("<F1>", lambda event: os.exit(0))

w = tk.StringVar()

labelFlash = tk.Label(root, bg='Black', width=root.winfo_screenwidth(), height=root.winfo_screenheight(),
                      anchor="center", text="Sample", fg="White", font="Times " , textvariable=w)
labelFlash.pack()
MSG="Hello World"
str_list=[]
for i in range(len(MSG)):
    str_list.append(MSG[:i+1])
words=str_list


indx=0
def update():
    global indx
    if indx>=len(words):
        indx=0
    w.set(words[indx])
    labelFlash.config(text=words[indx])
    indx+=1
    root.after(500, update)#500 ms


update()
root.mainloop()

推荐阅读