Page 404 -
P. 404
custom widgets and classes
But how does an object call a method?
To see in more detail how the new SoundPanel widgets use the methods in
the SoundPanel class, let’s look in more detail at just one of the methods.
What happens if someone clicks on the checkbox within the widget?
Hey, someone clicked
the checkbox. The event This is the code to the
handler for that is called “track_toggle()” method.
“track_toggle”. What happens The method takes a
now, SoundPanel class? single parameter.
def track_toggle(self):
if self.track_playing.get() == 1:
self.track.play(loops = -1)
else:
self.track.stop()
“self” identifies the
widget calling the
The method you need to add to your class should look familiar. This code method.
is almost the same as the track_toggle() event handler we created
before. The only difference is that this method is a little more selfish.
self identifies the widget calling the method
The methods in the class are going to be used for lots of objects, so the code
in the class needs some way to know which SoundPanel object it is working
with at any point in time. It does that with the self variable.
The self variable is passed to each of the methods in the class automatically
by Python and it identifies the current widget object being used. By adding
“self.” to the front of the object’s variable names in the class code, you
make sure the code is using the data that belongs to the current widget.
Let’s add some methods to the SoundPanel() class...
you are here 4 369

