2012-07-16 215 views
4

我有一個簡單的代碼來使用tkinter可視化一些數據。按鈕點擊被綁定到重繪下一個「幀」數據的功能。不過,我想要選擇以特定頻率自動重繪。在GUI編程方面,我非常青睞(我不需要爲此代碼做很多工作),所以我的大部分tkinter知識都來自於遵循和修改示例。我想我可以使用root.after來實現這一點,但我不太確定我是否理解其他代碼。我的方案的基本結構如下:使用tkinter的簡單動畫

# class for simulation data 
# -------------------------------- 

def Visualisation: 

    def __init__(self, args): 
     # sets up the object 


    def update_canvas(self, Event): 
     # draws the next frame 

     canvas.delete(ALL) 

     # draw some stuff 
     canvas.create_........ 


# gui section 
# --------------------------------------- 

# initialise the visualisation object 
vis = Visualisation(s, canvasWidth, canvasHeight) 

# Tkinter initialisation 
root = Tk() 
canvas = Canvas(root, width = canvasWidth, height = canvasHeight) 

# set mouse click to advance the simulation 
canvas.grid(column=0, row=0, sticky=(N, W, E, S)) 
canvas.bind('<Button-1>', vis.update_canvas) 

# run the main loop 
root.mainloop() 

道歉要求,我敢肯定,有一個明顯的和簡單回答的問題。非常感謝。

回答

12

使用Tkinter進行動畫或定期任務的基本模式是編寫一個繪製單個框架或執行單個任務的函數。然後,使用像這樣定期調用它:

def animate(self): 
    self.draw_one_frame() 
    self.after(100, self.animate) 

一旦你一旦調用這個函數,它會繼續十每秒的速度繪製幀 - 每100毫秒一次。如果您希望能夠在動畫啓動後停止動作,則可以修改代碼以檢查標誌。例如:

def animate(self): 
    if not self.should_stop: 
     self.draw_one_frame() 
     self.after(100, self.animate) 

你會再有一個按鈕,點擊後,將self.should_stopFalse

+0

非常感謝布賴恩;我做了類似的事情,但不知何故,我的事件綁定中有一件事弄亂了事情。現在都在工作。 – user1528634 2012-07-17 09:11:23

+0

如果允許無限期運行,第一個版本會導致錯誤的最大遞歸深度達到 – 2015-07-13 14:36:43

+2

@rahultyagi:不,因爲它不是遞歸函數,所以不可能超過最大遞歸深度。至少,不是字面意義上的。該函數不會自行調用,它只是安排自己在未來再次運行。堆棧深度永遠不會超過1. – 2015-07-13 14:39:35

1

我只是想補充布萊恩的回答。我沒有足夠的代表發表評論。

另一個想法是使用self.after_cancel()停止動畫。

所以......

def animate(self): 
    self.draw_one_frame() 
    self.stop_id = self.after(100, self.animate) 

def cancel(self): 
    self.after_cancel(self.stop_id)