如何使用for循环更新Tkinter Label/Canvas小部件中的文本



我在更新标签和画布中的文本时遇到问题。更新画布中的文本本身就很烦人。没有发现任何有用的东西。

我的项目在这里-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)
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()

最新更新