如何使用for循环更新Tkinter标签/画布小部件中的文本?

时间:2020-08-05 17:38:18

标签: python tkinter tkinter-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)

1 个答案:

答案 0 :(得分:0)

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()