python - Tkinter mouse event initially triggered -
i'm learning tkinter , cannot find solution problem here nor outside stackoverflow. in nutshell, events bind widgets triggered initialy , don't respond actions.
in example, red rectangle appears on canvas when run code, ,
color=random.choice(['red', 'blue'])
revealed event binding doesn't work after that:
import tkinter tk class application(tk.frame): def __init__(self, master=none): tk.frame.__init__(self, master) self.can = tk.canvas(master, width=200, height=200) self.can.bind('<button-2>', self.draw()) self.can.grid() def draw(self): self.can.create_rectangle(50, 50, 100, 100, fill='red') app = application() app.mainloop()
i use mac platform, haven't got clue role in problem. please point me @ mistake did here?
there 2 things here:
you should not calling
self.draw
when bind<button-2>
.when click
<button-2>
, event object sentself.draw
. thus, need make function accept argument, if not use it.
in all, script should (the lines changed in comment boxes):
import tkinter tk class application(tk.frame): def __init__(self, master=none): tk.frame.__init__(self, master) self.can = tk.canvas(master, width=200, height=200) ####################################### self.can.bind('<button-2>', self.draw) ####################################### self.can.grid() ####################### def draw(self, event): ####################### self.can.create_rectangle(50, 50, 100, 100, fill='red') app = application() app.mainloop()
Comments
Post a Comment