2016-01-24 50 views
2

所以我知道在Python窗口中,你可以使用這個..如何在Tkinter中通過字符動畫文本?

for char in introstring: 
    sleep(0.2) 
    sys.stdout.write(char) 
    sys.stdout.flush() 

,它會在0.2

速度顯示由字符在窗口中的文字,字符我怎麼能這個過渡進入Tkinter窗口?例如,我有文字:

canvas.create_text((720,454),text="Just in case you start to feel sniffily, or something",fill="white", font=('arial')) 

有沒有辦法得到同樣的動畫,但在Tkinter的GUI,我已成立?我聽說過有關.after的命令,但我似乎無法找到它如何適用於此。

+0

不使用'sleep' - 使用'root.after' - http://stackoverflow.com/questions/34939609/tkinter-text-animation – furas

回答

2

下面是一個非常簡單的例子,它將字符逐個字符地打印到畫布上,並在字符之間延遲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() 
+0

我只是想出來,並實現了它,它成功了!非常感謝! – Daijoubu

+0

@Daijoubu:如果我的回答對你有幫助,請考慮[接受](http://meta.stackexchange.com/a/5235)它。 –

相關問題