Page 351 -
P. 351
start and stop
Code Magnets Solution
A couple of buttons on a GUI ought to do it. Here’s the code to a
small tkinter program that starts and stops a sound file. You were
asked to rearrange the code magnets to make the program:
Import the required libraries.
from tkinter import *
import pygame.mixer
Create the GUI application window.
app = Tk()
app.title("Head First Mix")
Identify the DJ's track.
app.geometry('250x100+200+100')
sound_file = "50459_M_RED_Nephlimizer.wav"
mixer = pygame.mixer Start the sound system.
mixer.init() The “track_start()" function will respond
to the “Start" button-click event.
The “loops = -1" parameter to “play()"
def track_start():
The “track_stop()" function track.play(loops = -1) repeats the track until you stop it.
will respond to the “Stop" def track_stop():
button-click event. track.stop()
Load up the track sound file.
track = mixer.Sound(sound_file)
Create a button for start_button = Button(app, command = track_start, text = "Start")
“Start" and “Stop," then start_button.pack(side = LEFT)
connect each of them to
their event handlers. stop_button = Button(app, command = track_stop, text = "Stop")
stop_button.pack(side = RIGHT)
app.mainloop()
Start the GUI event loop.
Load this!
Download the sound tracks for this chapter from the Head First Programming
website. Be sure to put the sound files in the same directory/folder as your code.
316 Chapter 9