下面是一個非常簡單的例子,它將字符逐個字符地打印到畫布上,並在字符之間延遲500毫秒。
import Tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()
canvas_text = canvas.create_text(10, 10, text='', anchor=tk.NW)
test_string = "This is a test"
#Time delay between chars, in milliseconds
delta = 500
delay = 0
for i in range(len(test_string) + 1):
s = test_string[:i]
update_text = lambda s=s: canvas.itemconfigure(canvas_text, text=s)
canvas.after(delay, update_text)
delay += delta
root.mainloop()
此代碼已經在Python 2.6上測試過。要在Python 3中運行它,你需要將import
聲明改爲import tkinter as tk
下面是一個更爲複雜的例子,顯示輸入到一個文本輸入構件的文本。當輸入在Entry小部件中被按下時,文本被顯示。
#!/usr/bin/env python
''' animate text in a tkinter canvas
See http://stackoverflow.com/q/34973060/4014959
Written by PM 2Ring 2016.01.24
'''
import Tkinter as tk
class Application(object):
def __init__(self):
root = tk.Tk()
self.canvas = tk.Canvas(root)
self.canvas.pack()
self.canvas_text = self.canvas.create_text(10, 10, text='', anchor=tk.NW)
self.entry = tk.Entry(root)
self.entry.bind("<Return>", self.entry_cb)
self.entry.pack()
root.mainloop()
def animate_text(self, text, delta):
''' Animate canvas text with a time delay given in milliseconds '''
delay = 0
for i in range(len(text) + 1):
update_text = lambda s=text[:i]: self.canvas.itemconfigure(self.canvas_text, text=s)
self.canvas.after(delay, update_text)
delay += delta
def entry_cb(self, event):
self.animate_text(self.entry.get(), 250)
app = Application()
不使用'sleep' - 使用'root.after' - http://stackoverflow.com/questions/34939609/tkinter-text-animation – furas