2013-05-29 51 views
3

我想寫一個基本tkinter的例子,將顯示一個框架延伸框。此時下面的代碼將只打印最終結果,而不顯示框的移動。如何修復代碼,以便隨着時間的推移使用類似移動的代碼,以便隨着時間的推移修改形狀?動畫Tkinter

from tkinter import Tk, Canvas, Frame, BOTH 
from time import sleep 


class Example(Frame): 

    def __init__(self, parent): 
     Frame.__init__(self, parent) 
     self.parent = parent 
     self.parent.title("Board") 
     self.pack(fill=BOTH, expand=1) 
     self.canvas = Canvas(self)   
     self.ctr = 10 
     self.initUI() 


    def initUI(self): 
     print(self.ctr) 
     #The first four parameters are the x,y coordinates of the two bounding points. 
     #The top-left and the bottom-right. 
     r = self.canvas.create_rectangle((self.ctr * 10), 0, (self.ctr * 10 + 50), 50, 
      outline="#fb0", fill="#fb0") 
     ''' 
     canvas.create_rectangle(50, 0, 100, 50, 
      outline="#f50", fill="#f50") 
     canvas.create_rectangle(100, 0, 150, 50, 
      outline="#05f", fill="#05f") 
     '''   
     self.canvas.pack(fill=BOTH, expand=1) 

     if self.ctr > 0: 
      self.updateUI() 

    def updateUI(self): 
      self.ctr -= 1 
      sleep(1) 
      self.initUI() 



def main(): 

    root = Tk() 
    root.geometry("400x100+300+300") 
    ex = Example(root) 
    root.mainloop() 


if __name__ == '__main__': 
    main() 

回答

5

這應該讓你在那裏(你需要修復縮進,偏移量不正確,計數器不會被重置)。將來,確保在使用GUI的事件循環時不要調用睡眠。大多數GUI都有一種方法將某些東西掛接到它們的事件循環中(本例中爲root.after調用)。我所做的只是讓你的代碼部分工作 - 這不應該被看作是慣用python的指示。

from tkinter import Tk, Canvas, Frame, BOTH 
from time import sleep 

class Example(Frame): 

def __init__(self, parent): 
    Frame.__init__(self, parent) 
    self.parent = parent 
    self.parent.title("Board") 
    self.pack(fill=BOTH, expand=1) 
    self.canvas = Canvas(self) 
    self.ctr = 10 


def initUI(self): 
    print(self.ctr) 
    #The first four parameters are the x,y coordinates of the two bounding points. 
    #The top-left and the bottom-right. 
    r = self.canvas.create_rectangle((self.ctr * 10), 0, (self.ctr * 10 + 50), 50, 
     outline="#fb0", fill="#fb0") 
    ''' 
    canvas.create_rectangle(50, 0, 100, 50, 
     outline="#f50", fill="#f50") 
    canvas.create_rectangle(100, 0, 150, 50, 
     outline="#05f", fill="#05f") 
    ''' 
    self.canvas.pack(fill=BOTH, expand=1) 

    self.ctr += 1 
    if self.ctr > 0: 
     self.parent.after(1000, self.initUI) 

def main(): 

root = Tk() 
ex = Example(root) 
root.geometry("400x100+300+300") 
root.after(1000, ex.initUI) 
root.mainloop() 

if __name__ == '__main__': 
main()