python - 如何使用 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)
解决方案
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()
推荐阅读
- windows-installer - 通过 Advanced Installer 安装后如何使包在启动时自动运行?
- r - 从 R 中的多个 PRISM 栅格之一中提取值
- rust - BinaryHeap 是仅将 PartialEq 用于排序顺序还是用于真正的等价?
- performance - 如何在 jmeter html 仪表板中显示第 98 个(或任何自定义)百分位数?
- polymorphism - OpenAPI / Swagger 3.0:默认鉴别器值
- kubernetes - 如何从 Kubernetes 作业中的所有 pod 获取日志?
- video - 叠加层中的ffmpeg延迟视频
- python - 尝试在 Django 中上传图像时没有这样的文件或目录
- java - 为什么 HashMap 允许重复,而 StringBuilder 不能正确反转?
- flutter - Flutter:在容器底部放置一个分隔器?