动态添加项目到Tkinter Canvas

时间:2010-05-13 02:01:22

标签: python dynamic canvas tkinter

我正在尝试学习Tkinter,目标是能够创建一个“实时”范围来绘制数据。作为测试,每次按下“绘制”按钮时,我都会尝试在画布上绘制多边形。三角形位置是随机的。我有两个问题:

  1. 一旦程序启动,画布上就会出现一个三角形,为什么以及如何解决这个问题?

  2. 当我按下按钮时,它不会绘制任何三角形,至少没有我能看到的。

  3. CODE


    from Tkinter import *
    
    from random import randint
    
    class App:
    
        def __init__(self,master):
    
            #frame = Frame(master)
            #frame.pack(side = LEFT)
    
            self.plotspc = Canvas(master,height = 100, width = 200, bg = "white")
            self.plotspc.grid(row=0,column = 2, rowspan = 5)
    
            self.button = Button(master, text = "Quit", fg = "red", \
                                 command = master.quit)
            self.button.grid(row=0,column=0)
    
            self.drawbutton = Button(master, text = "Draw", command = \
                                   self.pt([50,50]))
            self.drawbutton.grid(row = 0, column = 1)        
    
        def pt(self, coords):
            coords[0] = coords[0] + randint(-20,20)
            coords[1] = coords[1] + randint(-20,20)
            x = (0,5,10)
            y = (0,10,0)
            xp = [coords[0] + xv for xv in x]
            yp = [coords[1] + yv for yv in y]
            ptf = zip(xp,yp)
            self.plotspc.create_polygon(*ptf)        
    
        if __name__ == "__main__":
            root = Tk()
            app = App(root)
            root.mainloop()
    

1 个答案:

答案 0 :(得分:5)

command=self.pt([50,50])(您在构建Draw按钮的Button调用中使用)立即执行您要告诉它执行的调用,并绑定结果( None}至command。相反,请使用相同的内容:

, command=lambda: self.pt([50, 50]) )

在每次按下该按钮时延迟执行调用。