简体   繁体   English

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

[英]How to Update text in Tkinter Label/Canvas widget using for loop?

I am having issues in updating text in label as well as in canvas.我在更新 label 和 canvas 中的文本时遇到问题。 Updating text in canvas itself was tiresome.更新 canvas 中的文本本身就很烦人。 Didn't find anything useful.没找到有用的。

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

What I wish to do - Display a paragraph, word by word (with some delay in between)我想做什么 - 逐字显示段落(中间有一些延迟)

What I thought while writing the code - Paragraph will be in file.我在编写代码时的想法 - 段落将在文件中。 The code will read the paragraph, extract 1st word & put them into label widget.代码将读取段落,提取第一个单词并将它们放入 label 小部件中。 After a delay, 1st word will disappear & 2nd word will be put to display.延迟后,第一个单词将消失,第二个单词将被显示。 And so on.等等。

What the code actually does - Instead of showing the whole word, its showing 1st letter of 1st word.代码的实际作用 - 不是显示整个单词,而是显示第一个单词的第一个字母。 I used for loop to update the text displayed in label widget, but it doesn't update/refresh.我使用 for 循环来更新 label 小部件中显示的文本,但它不会更新/刷新。

Here is the code snippet -这是代码片段 -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM