2016-04-30 186 views
1

我是tkinter的新手,並撰寫一個簡單的骨架程序,在畫布上繪製五條線。我希望畫布在每一個新行後更新。我幾乎在那裏(!),但畫布不會更新,直到所有行被計算出來。所有關於如何修復我的代碼的建議將非常感謝。謝謝!tkinter中的畫布更新

from tkinter import * 
from time import sleep 

class app(): 
    def __init__(self): 
     self.root = Tk() 
     self.canvas = Canvas(self.root, width=300, height=300) 
     self.canvas.pack() 

     self.go() 
     self.root.mainloop() 

    def go(self): 
     for i in range(5): 
      self.drawLine(i) 
      sleep(1) # simulate computation of next value 

    def drawLine(self, n): 
     self.canvas.create_line(0, 0, 50, n * 50 + 10) 
     # now I would like canvas to be updated with the new line added 

app() 
+3

drawLine方法結束時的self.root.update()應該執行此操作。 – Mirac7

+0

謝謝,現在代碼按預期工作。 – Beno

回答

0

sleep與tkinter不兼容,因爲它阻塞了事件循環。一起使用它們通常會導致你的tkinter窗口凍結。睡五秒鐘可能會導致您的計算機出現這種情況,但仍然非常不可靠。如果你以後想顯示15行而不是5行,你的程序幾乎可以保證停止工作。

這裏的正確解決方案是使用根對象的after方法。 after在一定的時間內執行指定的功能。以下是您的代碼的一個工作示例:

from tkinter import * 

class app(): 
    def __init__(self): 
     self.root = Tk() 
     self.canvas = Canvas(self.root, width=300, height=300) 
     self.canvas.pack() 

     self.line_counter = 0 
     self.draw_next_line() 
     self.root.mainloop() 

    def draw_next_line(self): 
     self.canvas.create_line(0, 0, 50, self.line_counter * 50 + 10) 
     self.line_counter += 1 
     if self.line_counter != 5: 
      # call this function again after 1000 milliseconds 
      self.root.after(1000, self.draw_next_line) 

app()