SUSHIL TIWARI
SUSHIL TIWARI

Reputation: 1

How to use event binding inside class in tkinter, Dealing with event and self

When i was trying to event bind inside my class, binding event creates argument error. Codes are written below-

class Login_App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.btn_lgin = ttk.Button(self, text="Login")
        self.btn_lgin.grid()
        self.btn_lgin.bind('<Return>', lambda: Login(self=self))

    def Login(self):
        '''I need "Self" in some codes, cant remove it'''
        print("Clicked")

if __name__ == "__main__":
    app = Login_App()
    app.mainloop()

Upvotes: 0

Views: 825

Answers (1)

Thalis
Thalis

Reputation: 176

You should only do a minor change:

When calling a function with a parameter self inside a class self is not an actual parameter so you don't need to pass it as one.
What you should do is:

self.btn_lgin.bind('<Return>', lambda x: self.Login())

Be aware that when you change this you should also change: lambda: to lambda x: because lambda: gets one positional argument when you've passed zero, leading to TypeError

Upvotes: 1

Related Questions