Page 279 -
P. 279
button press rehearsal
The GUI program’s now ready for
a screentest
Here’s what your GUI program should look like now:
from tkinter import *
import pygame.mixer
sounds = pygame.mixer
sounds.init()
correct_s = sounds.Sound("correct.wav")
wrong_s = sounds.Sound("wrong.wav")
number_correct = 0 The buttons are now
number_wrong = 0 connected to event-
handling functions.
def play_correct_sound():
Python’s “global” global number_correct
number_correct = number_correct + 1
keyword lets
you adjust the correct_s.play()
value associated def play_wrong_sound():
with a variable global number_wrong
created outside
number_wrong = number_wrong + 1
the function. wrong_s.play()
app = Tk()
app.title("TVN Game Show")
app.geometry('300x100+200+100')
b1 = Button(app, text = "Correct!", width = 10, command = play_correct_sound)
b1.pack(side = 'left', padx = 10, pady = 10)
b2 = Button(app, text = "Wrong!", width = 10, command = play_wrong_sound)
b2.pack(side = 'right', padx = 10, pady = 10)
app.mainloop()
print(str(number_correct) + " were correctly answered.")
print(str(number_wrong) + " were answered incorrectly.")
244 Chapter 7