Jayron Hubbard
Jayron Hubbard

Reputation: 121

click event in class in tkinter

I am trying to create a click event in order to easily see coordinates on my grid. I have been following the effbot tutorial, but it doesn't seem to work within my class. here is what I have:

class Keyboard(Frame):

    def __init__(self, root, press):
        Frame.__init__(self, root)
        self.press = press
        self.createWidgets()
        self.bind("<Button-1>", self.click)

    def click(event):
        print("clicked at", event.x, event.y)

When I run this and click somewhere it says:

"TypeError: click() takes 1 positional argument but 2 were given"

Upvotes: 2

Views: 3590

Answers (2)

user2555451
user2555451

Reputation:

click is a method of the class Keyboard. This means that it will always be passed an implicit first argument (usually called self) which is a reference to the class itself.

You need to define click like so:

def click(self, event):

Otherwise, event will receive the argument for self and the argument that should be for event will be left over.

Here is a reference on self in Python: What is the purpose of self?

Upvotes: 2

Neel
Neel

Reputation: 21243

You are defining class function click so you have to pass first argument as self class object

so please change it

class Keyboard(Frame):

    def __init__(self, root, press):
        Frame.__init__(self, root)
        self.press = press
        self.createWidgets()
        self.bind("<Button-1>", self.click)

    def click(self, event):
        print("clicked at", event.x, event.y)

Upvotes: 2

Related Questions