Page 391 -
P. 391

function in a function


          The new function contains other functions


           With all the code gathered together in a new function, the code for the
           create_gui() function looks like this:

                        from tkinter import *
                        import pygame
         This function is
         LOCAL to the   def create_gui(app, mixer, sound_file):          Note: when this function is called,
        “create_gui()”                                                   it is expecting three parameters.
        function.           def track_toggle():
                                if track_playing.get() == 1:
                                                                  These are the event
                                    track.play(loops = -1)
                                else:                             handlers, which are
         This function is               track.stop()               linked to the “command”
                                                                   parameter of each widget.
         LOCAL, too.
                            def change_volume(v):
        When this               track.set_volume(volume.get())
        function is
        called, it starts
        executing from       track = mixer.Sound(sound_file)
        here.               track_playing = IntVar()

                            track_button = Checkbutton(app, variable = track_playing,
                                                         command = track_toggle, text = sound_file)
                            track_button.pack(side = LEFT)
         As always,         volume = DoubleVar()
          the calls to
                            volume.set(track.get_volume())
         “pack()” add       volume_scale = Scale(variable = volume, from_ = 0.0, to = 1.0,
          the widgets to                             resolution = 0.1, command = change_volume,
          the GUI.                                      label = "Volume", orient = HORIZONTAL)

                            volume_scale.pack(side = RIGHT)





                                                                               A function-in-a-
           Do you notice anything strange? The new function actually has two other
           functions inside it. Python (and several languages) lets you create local   function is called
           functions. A local function is just a function inside a function.
                                                                               a local function.
           Let’s see why they’re important for the DJ’s program.



           356    Chapter 10
   386   387   388   389   390   391   392   393   394   395   396