Home > Blockchain >  Tkinter - Bind event handling in function
Tkinter - Bind event handling in function

Time:06-23

I'm trying to implement a function where a tk-Button xor Keyboard Button Press are running the same function.

Here is a code example:

from tkinter import *


root = Tk()
root.geometry("800x600")
root.title("Event Testing")

def on_closing():
    root.destroy()

root_button = Button(root, text="Exit", command=on_closing)
root_button.place(x=400, y=300, anchor=CENTER)

# root.bind("<Escape>", on_closing)

root.mainloop()

When i bind the <Escape> Button and press it following Error raises:

TypeError: on_closing() missing 1 required positional argument: 'event'

If i put an event variable into the function like def on_closing(event) the <Escape> Button works but the tk-Button is raising the same Error again.

Is there a better alternative then binding <Button-1> to the tk-Button or creating one function with an event variable and one without and splitting this up.

EDIT:

I've think i found a bit ugly but functioning workaround.

root_button = Button(root, text="Exit", command=lambda: on_closing(""))

If there is still a better way to do it i would like to hear it ;).

CodePudding user response:

Here is a solution which works, I used a lambda function instead of on_closing() function for root.bind(). Another option might be programming all in OOP.

from tkinter import *


root = Tk()
root.geometry("800x600")
root.title("Event Testing")

def on_closing():
    root.destroy()

root_button = Button(root, text="Exit", command=on_closing)
root_button.place(x=400, y=300, anchor=CENTER)

root.bind("<Escape>", lambda x: root.destroy())

root.mainloop()

EDIT:

Ok, another try. With event=None, so the event is defined as default none. You don't get the Error because of the definition and it's the same function.

from tkinter import *

def on_closing(event=None):
    root.destroy()

root = Tk()
root.geometry("800x600")
root.title("Event Testing")
root.bind("<Escape>", on_closing)
    
root_button = Button(root, text="Exit", command=on_closing)
root_button.place(x=400, y=300, anchor=CENTER)

root.mainloop()
  • Related