Why is Button not working in tkinter, when i click it it shows an error

Question:

I am trying this code. I want to use don function for bind() and command. It is showing don() missing 1 required positional argument: ‘Event’. how to fix it

my code

from tkinter import *
root = Tk()
root.geometry("600x500")

def don(Event):
    print("hello")


root.bind("<Return>", don)
btn1 = Button(root, text="check! ", command=don).pack()

root.mainloop()
Asked By: Harsh Gupta

||

Answers:

All you need to do is get rid of Event or as the person said above me Event=None. Depends if you are going to build on it later and add some parameters

from tkinter import *
root = Tk()
root.geometry("600x500")

def don():
    print("hello")


root.bind("<Return>", don)
btn1 = Button(root, text="check! ", command=don).pack()

root.mainloop()
Answered By: HarrisonT

The root of the problem is that a function called via bind automatically gets an event parameter, but a function called by the command option does not. The trick is to make a function that can be called with or without a parameter, and which doesn’t use the parameter (since it isn’t guaranteed to be there).

The normal way to do this is to make the event parameter options, which is done like this:

def don(event=None):
    print("hello")

This will cause event to be set to None if it’s not passed in, which is harmless since the function doesn’t use the event parameter.

Answered By: Bryan Oakley
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.