user339860
user339860

Reputation: 137

Dynamically add items to Tkinter Canvas

I'm attempting to learn Tkinter with the goal of being able to create a 'real-time' scope to plot data. As a test, I'm trying to draw a polygon on the canvas every time the 'draw' button is pressed. The triangle position is randomized. I have two problems:

  1. There is a triangle on the canvas as soon as the program starts, why and how do I fix this?
  2. It doesn't draw any triangles when I press the button, at least none that I can see.

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

Upvotes: 1

Views: 2565

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882701

command=self.pt([50,50]) (that you use in the Button call which builds the Draw button) immediately executes the call you're telling it to execute, and binds the result (None) to command. Use, instead, in that same:

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

to delay the execution of the call to each time that button will be pressed.

Upvotes: 5

Related Questions