I bound the event <Return> to a Button, thinking that this would cause the command to be run after hitting Enter:
Button(self.f, text="Print", command=self.Printer).pack(side=RIGHT, padx=10, pady=10)
self.button1 = Button(self.f, text="search", command=self.search)
self.button1.bind('<Return>', self.search)
self.button1.pack(side=RIGHT, padx=10, pady=10)
But it doesn’t do anything. What must I do for self.search to be run when Enter is pressed?
Your code looks fine, but note that the focus must be on the button if you want
Returnto callself.search(). You can change the focus from widget to widget by pressingTab. The widget in focus is outlined with a thin black line. You may have to pressTabone or more times to move the focus to the button before pressingReturn.If you want
Returnto work anywhere in the GUI window, then changeto
where
root = tk.Tk().For example, compare
button.bindwithmaster.bindin the code below:Alternatively, you could use
Doing it this way, pressing
Returncallsself.search()only when the button has the focus, but the button gets the focus when the app begins.Regarding the use of
*argsand**kwargs:**kwargsallows arbitrary keyword arguments to be passed to__init__.When
**kwargsis used in a function definition like this:and we instantiate
SimpleApplike this:then Python sets
kwargsto a dict containing the keyword arguments, e.g.{'title':'Hello, world'}. Note that**kwargsis Python syntax which can only be used in function definitions and function calls (see below), butkwargsitself is just a dict.kwargsis then passed toFrame:Now, when **kwargs is used in a function call, the key-value pairs in the
kwargsdict get expanded so that the above function call is equivalent toSince
Framecan take numerous keyword arguments, and I don’t know them all and don’t wish to enumerate them, it is advantageous to use**kwargs.Note also that even if new keyword arguments were added to
Frameat some later date, my code will still work, whereas if I spelled out the keywords explicitly then my code would not automatically “upgrade” ifFrame‘s allowable keywords were to change.*args, similarly, allows you to include arbitrary positional arguments tosearch:Python sets
argsto a list containing all the positional arguments sent tosearchwhensearchis called.I used *args here because
self.searchis called with no arguments or one argument.When you say
self.search()is called with no argumens when the button is clicked. But when you sayself.search(event)is called with one argument when theReturnkey is pressed.eventis a Tkinter.Event which has attributes (time, state, type, widget, x, y, etc) which allow you to learn more about what event took place.Another, perhaps better, way to define
searchwould have beenThis would have made it clear that
searchmay be passed 0 or 1 arguments, and not simply and arbitary number of arguments. It also would have provided easier access toeventif an event were passed tosearch.Reference:
explanation.