3

我正在尝试编写一个基本的 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() 
4

1 回答 1

5

这应该会让你走到那里(你需要修复缩进,偏移不正确并且计数器不会被重置)。将来,例如,当您使用 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()
于 2013-05-29T22:16:03.460 回答