2013-05-29 46 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()