Button Widget and Key Binding Problem

Wildman best_lay at yahoo.com
Tue Oct 18 22:13:51 EDT 2016


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.

-- 
<Wildman> GNU/Linux user #557453
May the source be with you.



More information about the Python-list mailing list