### # multiplication_game.py # # author: Kristina Striegnitz # # version: 3/10/2010 # # A GUI application that lets the user practice multiplication of # numbers up too 20. ### from Tkinter import * import random def check_solution(solution, n1, n2): """ Checks whether the solution input by the user is the same as the correct solution. Returns the message string to be displayed to the user in the GUI. """ user_sol = int(solution.get()) real_sol = int(n1.get()) * int(n2.get()) if user_sol == real_sol: return str(real_sol)+" is right. Well done!" else: return "Solution is "+str(real_sol)+". Try again." def new_problem(n1, n2, solution, message): """ Randomly generates a new multiplication problem (two new numbers) and displays it in the GUI. """ n1.set(random.randint(0,20)) n2.set(random.randint(0,20)) solution.set("") message.set("") def main(): main_window = Tk() main_window.title("Test Window") main_window.geometry("500x100") # four frames stacked on top of each other frame1 = Frame(main_window) frame1.pack(side="top") frame2 = Frame(main_window) frame2.pack(side="top") frame3 = Frame(main_window) frame3.pack(side="top") frame4 = Frame(main_window) frame4.pack(side="top") # content of frame 1: multiplication problem and entry box for the # user to enter the solution n1 = StringVar() n1.set(random.randint(0,20)) n1_label = Label(frame1, textvariable=n1) n1_label.pack(side="left") op = Label(frame1, text="x") op.pack(side="left") n2 = StringVar() n2.set(random.randint(0,20)) n2_label = Label(frame1, textvariable=n2) n2_label.pack(side="left") eq = Label(frame1, text="=") eq.pack(side="left") solution = StringVar() solution_entry = Entry(frame1, width=5, textvariable=solution) solution_entry.pack(side="left") # content of frame 2: response message message_text = StringVar() message = Label(frame2, textvariable=message_text) message.pack() # content of frame 3: submit and next button submit_b = Button(frame3, text="Submit", command = lambda: message_text.set( check_solution(solution_entry, n1, n2))) submit_b.pack(side="left") next = Button(frame3, text="Next", command = lambda: new_problem(n1, n2, solution, message_text)) next.pack(side="right") # content of frame 4: quit button quit_b = Button(frame4, text="Quit", command=main_window.destroy) quit_b.pack(side="right") main_window.mainloop() main()