Aug-04-2022, 07:10 PM
(This post was last modified: Aug-04-2022, 07:10 PM by deanhystad.)
You should read the documentation. This describes what arguments are passed to the bound event callback.
https://docs.python.org/3/library/tkinte...d-events-1
In your example you are binding a key code (<Return>, <Escape>), so the argument passed to your functions is an event that contains the key that was pressed.
This is a little program that displays the event in an Entry widget. You can select the entry and type and it works like normal, but it you press <Return> or <Escape> an text is replaced by the event info.
https://docs.python.org/3/library/tkinte...d-events-1
In your example you are binding a key code (<Return>, <Escape>), so the argument passed to your functions is an event that contains the key that was pressed.
This is a little program that displays the event in an Entry widget. You can select the entry and type and it works like normal, but it you press <Return> or <Escape> an text is replaced by the event info.
import tkinter as tk class MainWindow(tk.Tk): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.title("Test UI") self.bind("<Return>", self.keypress) self.bind("<Escape>", self.keypress) self.text = tk.StringVar(self, "") tk.Entry(self, textvariable=self.text, width=80).pack(padx=20, pady=20) def keypress(self, event): self.text.set(str(event)) MainWindow().mainloop()If you don't use the event you can ignore it. The linter in my IDE does not like functions arguments that aren't used in the function, so I use a place holder instead of an argument.
def keypress(self, _): self.text.set("something happened")The "_" in the function declaration tells the reader that one argument is passed, but not used by the function. Unfortunately you can only use one "_". If there are multiple arguments to ignore I might do this:
def keypress(self, *_):But I cannot do this:
def keypress(self, *_, **_):I can also use a lambda expressing to remove or replace the event argument.
self.bind("<Return>", lambda event:self.keypress("Return was pressed") self.bind("<Escape>", lambda event:self.keypress("Escape was pressed") def keypress(self, msg): self.text.set(msg)Here the lambda expression consumes the "event" argument and passes along a different argument.