Add master.bind(...)
commands to the __init__
method:
def __init__(self, master):
frame = Frame(master)
frame.pack()
master.bind('1', self.gpio25)
master.bind('2', self.gpio24)
master.bind('3', self.gpio23)
...
master.bind('1', self.gpio25)
binds the keypress 1
event to the method call self.gpio25(event)
.
You will need 7 more master.bind
calls -- one for each key.
Next, modify the definition of the callback functions. You will need to add a second argument, event
, to each of them. Change, for example,
def gpio25(self):
to
def gpio25(self, event = None):
Explanation:
When you use the bind
method, you are binding an Event
to a callback function (e.g. self.gpio25
). Pressing a key is a KeyPress Event. Information about the event is sent to the callback in an Event object. Thus the callback function must take one argument.
See Tkinter events and bindings for more information.
Buttons
work differently. Their callback functions are called with zero arguments.
Since we are using the same callback function, self.gpio25
, as both a Keypress event callback and as a Button callback, it must be a function that can take zero or one argument.
In Python, the way to do that is to define gpio25
with a call signature like:
def gpio25(self, event = None):
self
is an instance of the class App
. self.gpio25
is a bound method with self
bound as its first argument. So calling self.gpio25()
will call the gpio25
function with self
as the first argument (and the local variable event
will be assigned the value None
). Calling self.gpio25(foo)
will call gpio25
with self
as the first argument, and foo
as the second argument (and the local variable event
will be assigned the value foo
).
In your case, the value assigned to event
does not really matter, since event
is not used in the body of gpio25
. We just needed to set up self.gpio25
to be ready to accept zero or one argument.