Button Widget and Key Binding Problem

MRAB python at mrabarnett.plus.com
Tue Oct 18 23:39:03 EDT 2016


On 2016-10-19 03:13, Wildman via Python-list wrote:
> I am working on a program with a GUI created with Tkinter.  I
> want to enable key bindings for the button widgets.  Below is
> some of the code to show how the window and button widget was
> created.  The button calls a routine that will load an image.
>
> <code>
> class Window(tk.Frame):
>
>     def __init__(self, master=None):
>         tk.Frame.__init__(self, master)
>         self.master = master
>         root.bind("<Alt-l>", self.load_image)
>         root.bind("<Alt-L>", self.load_image)
>         self.init_window()
>
>     def init_window(self):
>         self.loadButton = tk.Button(self,
>                                     text="Load Image",
>                                     underline=0,
>                                     width=10,
>                                     command=self.load_image)
>
>     def load_image(self):
>         # code to load an image
> </code>
>
> When I click the load button everything works as expected.
> But if I hit the hot key I get this error:
>
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__
>     return self.func(*args)
> TypeError: load_image() takes exactly 1 argument (2 given)
>
> The key binding is making the call with an extra argument.
> If I change the definition for the load_image routine for
> an additional argument, the key binding works but the button
> click produces this error:
>
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__
>     return self.func(*args)
> TypeError: load_image() takes exactly 2 arguments (1 given)
>
> As a workaround I changed the binding code to call a different
> routine named launch_load_image and that routine calls load_image:
>
>     def launch_load_image(self, _):
>         self.load_image()
>
> Both the key bindings and the button click work.  My question
> is whether my workaround is the correct way?  Could my key
> binding code be wrong in some way?  An insight appreciated.
>
The 'bind' method passes an 'event' object when it calls; the 'command' 
callback doesn't.

You don't care about the 'event' object anyway, so you can just define a 
single method with a default argument that you ignore:

     def load_image(self, event=None):
         # code to load an image




More information about the Python-list mailing list