Tkinter 文本小部件逐行着色动画
Tkinter Text Widget Line By Line Colorizing Animation
我想创建一个动画,其中文本小部件的每一行都突出显示 0.5 秒。我发现这可以通过使用标签来完成。
root = Tk()
text = Text(root,width=28, height=20)
text.pack()
for i in range(int(text.index('end-1c').split('.')[0])):
text.tag_add("Tag", f"{i + 1}.0", f"{i + 1}.0+1lines")
text.tag_config("Tag", background="khaki")
#Some waiting for 0.5 seconds
text.tag_remove("Tag",f"{i + 1}.0", f"{i + 1}.0+1lines")
root.mainloop()
我已经尝试 time.slepp
但这不起作用(它只会冻结屏幕)。
我知道 tkinter
中有一些方法可以做到这一点,但我在互联网上找不到任何解决方案或答案。
试试这个:
import tkinter as tk
def function(i=0):
text.tag_remove("Tag", "0.0", "end")
# If we reached the end, stop
if i == int(text.index("end-1c").split(".")[0]):
return None
text.tag_add("Tag", f"{i + 1}.0", f"{i + 1}.0+1lines")
# After 0.5 sec run the function again with i = i + 1
text.after(500, function, i+1)
root = tk.Tk()
text = tk.Text(root)
text.pack()
text.insert("end", "\n".join(map(str, range(10))))
text.tag_config("Tag", background="red")
button = tk.Button(root, text="Click me", command=function)
button.pack()
root.mainloop()
它使用 for
循环,使用 .after
脚本实现。每次调用 function
时 i
递增,其中 i
的默认值为 0。
我想创建一个动画,其中文本小部件的每一行都突出显示 0.5 秒。我发现这可以通过使用标签来完成。
root = Tk()
text = Text(root,width=28, height=20)
text.pack()
for i in range(int(text.index('end-1c').split('.')[0])):
text.tag_add("Tag", f"{i + 1}.0", f"{i + 1}.0+1lines")
text.tag_config("Tag", background="khaki")
#Some waiting for 0.5 seconds
text.tag_remove("Tag",f"{i + 1}.0", f"{i + 1}.0+1lines")
root.mainloop()
我已经尝试 time.slepp
但这不起作用(它只会冻结屏幕)。
我知道 tkinter
中有一些方法可以做到这一点,但我在互联网上找不到任何解决方案或答案。
试试这个:
import tkinter as tk
def function(i=0):
text.tag_remove("Tag", "0.0", "end")
# If we reached the end, stop
if i == int(text.index("end-1c").split(".")[0]):
return None
text.tag_add("Tag", f"{i + 1}.0", f"{i + 1}.0+1lines")
# After 0.5 sec run the function again with i = i + 1
text.after(500, function, i+1)
root = tk.Tk()
text = tk.Text(root)
text.pack()
text.insert("end", "\n".join(map(str, range(10))))
text.tag_config("Tag", background="red")
button = tk.Button(root, text="Click me", command=function)
button.pack()
root.mainloop()
它使用 for
循环,使用 .after
脚本实现。每次调用 function
时 i
递增,其中 i
的默认值为 0。