Reputation: 77
No matter how I try it I keep getting the error that I need to send an argument to the event.
and yes before you say to go look at the documentation. I have looked at it but it doesn't help with what I'm doing because it is never inside a class.
from tkinter import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.callback()
self.initUI()
self.mainloop()
def callback(self, event):
print("made it")
def initUI(self):
canvas = Canvas(self, height = 300, width = 300)
canvas.create_rectangle(1.5,1.5,40,40, tag = "obj1")
canvas.tag_bind("obj1", '<Button-1>', callback) #where I assume the problem is happening
A = App()
EDIT: callback keeps saying it needs another argument but I don't know what it needs
Upvotes: 1
Views: 6018
Reputation: 385810
You have defined your callback to take two arguments: self
(meaning, it's a method on an object) and event
. When you call it directly with self.callback()
, self
gets automatically passed, but you aren't passing in an event. That is why you get the error saying it needs another argument. It expects two, but is only getting one.
It's unclear what you are attempting to do by directly calling your callback, but a quick fix is to make the event
attribute optional so you can call the callback directly or via a binding. Of course, this will only work if your binding doesn't actually use the event
parameter. If it does, when calling it without an event
you can expect it to fail.
Here's an example of making the event
parameter optional:
def callback(self, event=None):
print("made it")
That solves one problem, but you also have to change how your binding is defined or your code will crash when it starts up. You need to prepend self
to the callback:
canvas.tag_bind("obj1", '<Button-1>', self.callback)
When callback is called, self
again is automatically passed as the first argument. Tkinter will automatically add the event
parameter.
Pedantically speaking, you should not be calling mainloop()
inside of __init__
. That prevents the App
object from fully being constructed. The proper way to do it is to call mainloop
outside of the constructor:
A = App()
A.mainloop()
Upvotes: 4