Python 动画特金特

Python 动画特金特,python,tkinter,animated,Python,Tkinter,Animated,我试图写一个基本的tkinter示例,展示一个框在一个框架上伸展。此时,下面的代码将只打印最终结果,而不显示方框移动。如何修复代码,使其在不使用move之类的工具的情况下随时间工作,以便以后可以随时间修改形状 from tkinter import Tk, Canvas, Frame, BOTH from time import sleep class Example(Frame): def __init__(self, parent): Frame.__init_

我试图写一个基本的tkinter示例,展示一个框在一个框架上伸展。此时,下面的代码将只打印最终结果,而不显示方框移动。如何修复代码,使其在不使用move之类的工具的情况下随时间工作,以便以后可以随时间修改形状

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() 

这应该可以让你达到一半(你需要修正缩进,偏移量不正确,计数器不能复位)。将来,请确保在使用GUI的事件循环时不要调用sleep。大多数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()