Jumping between functions in tkinter - python

so I am working on this school project and I need to be able to run the random number generator then if it is 1 go to the headspinner module but if it is 2 go to the tailspinner module. After that the code should add up the score and print it to the user.
Any advice on how to jump from one function to another in my code would be much appreciated thank you.
from tkinter import * # access tkinter library
import random # get random number generator
money = 100
#create coin flip module
def coinFlip():
flip = random.randint(1, 2)
if flip == 1:
headspinner()
else:
tailspinner()
#create headspinner module
def headspinner():
global money
head = random.randint(1, 2)
if head == 1:
money = money + 30
else:
money = money - 25
#create tailspinner module
def tailspinner():
global money
tail = random.randint(1, 4)
if tail == 1:
money = money + 2
elif tail == 2:
money = money + 5
elif tail == 3:
money = money + 10
else:
money = money + 15
#gains or losses module
def upordown():
global money
if money > 100:
screen.itemconfig(message, text = f"Congratulations, you won ${(money - 100):.2f}", font = ("Calibri", "18"))
else:
screen.itemconfig(message, text = f"Congratulations, you won ${(100 - money):.2f}", font = ("Calibri", "18"))
#create pop up box
root = Tk()
#creating canvas
screen = Canvas (root, height = 600, width = 800, bg = "lightgreen")
screen.pack()
#flip button
go = Button(root, text = "Flip", cursor = "hand2", command = coinFlip)
goButton = screen.create_window(400, 530, window = go)
#cerate title
title = screen.create_text(400, 100, text = "Welcome to Flip and Spin", font = ("Calibri", "35"))
#text for instructions
text1 = Label(root, text = "Welcome to the Flip and Spin game! \nThis game includes a quick fate of what you could encounter. \nIt starts off with a fast flip of a coin followed by a dizzying spin of a spinner. \nCome and play to decide if you will lose money, \nmake your money back, or win some easy money!", font = ("Calibri", "20"), justify = CENTER, bg = "light green")
text1label = screen.create_window(400, 300, window = text1,)
#text for final results
message = screen.create_text(400, 400, text = "Results", font = ("Calibri", "18"))
#close canvas
mainloop()

You are already switching from function to function in def coinFlip.
You just need to put everything together.
Here's a simple example to get you started:
from tkinter import Tk, Button, Label, X, LEFT, RIGHT
import random
money = 100
#create coin flip module
def coin_flip():
flip = random.randint(1, 2)
if flip == 1:
headspinner()
else:
tailspinner()
#create headspinner module
def headspinner():
global money
head = random.randint(1, 2)
if head == 1:
money = money + 30
else:
money = money - 25
text.config(text=f"Headspinner: {money}", bg="#aaafff")
#create tailspinner module
def tailspinner():
global money
tail = random.randint(1, 4)
if tail == 1:
money = money + 2
elif tail == 2:
money = money + 5
elif tail == 3:
money = money + 10
else:
money = money + 15
text.config(text=f"Tailspinner: {money}", bg="#ffaaaa")
def show_result():
global money
text.config(text=f"Result: {money}.\nClick the Flip button to start over.", bg="#fffaaa")
money = 100 # reset
root = Tk()
root.title("Game")
# the text here changes when the buttons are pressed
text = Label(root, text="Welcome to the Flip and Spin game!", font = ("Calibri", "18"))
text.pack()
rules = Label(root, text="This game includes a quick fate of what you could encounter. \nIt starts off with a fast flip of a coin followed by a dizzying spin of a spinner. \nCome and play to decide if you will lose money, \nmake your money back, or win some easy money!", font = ("Calibri", "10"))
rules.pack()
# click the button to run the command and change the text in the Label
flip_button = Button(root, text="Flip", command=coin_flip, fg="blue")
flip_button.pack(fill=X, side=LEFT, expand=True)
# click the button to run the command and change the text in the Label
result_button = Button(root, text="Result", command=show_result, fg="blue")
result_button.pack(fill=X, side=RIGHT, expand=True)
root.mainloop()

Related

Python Random Math Equation Generator program

I've currently been creating a math equation generator program that will ask you random multiplication questions. I have been having trouble with the if statements where ans == answer will be equal dependent on the user's input (correct answer). However, my program does not see it as equal despite being the same value with example from printing ans and answer which shows they are the same value. I don't know if I am doing something wrong and I would like to know a method of fixing my issue.
Also when I tried to create for and while loops for the generating the equations, it would print them all out at once, is there a way to also make it so that the loop will not print a new random equation until the user gets the answer right?
from tkinter import *
from random import *
import random
import time
import tkinter as tk
import math
import operator
from tkinter import messagebox
#This is for creating the tkinter window and fixing the specified dimensions into place
root = tk.Tk()
root.geometry("900x600")
#This section creates the canvas and its specifications
canvas_width = 900
canvas_height = 500
c = Canvas(root, width=canvas_width, height=canvas_height, bg="pink")
c.pack()
def quitgame():
root.destroy()
class Game_Images:
#Background Image
bg = PhotoImage(file="../Data/sidescroll background flip.gif")
bg = bg.zoom(2)
c.create_image(0,0, anchor=NW, image=bg)
#Insert Image of Enemy
enemy = PhotoImage(file="../Data/monke2.png")
enemy1 = c.create_image(0,260, anchor=NW, image=enemy)
#Insert image of playable character
player = PhotoImage(file="../Data/monke2.png")
player1 = c.create_image(0,325, anchor=NW, image=player)
g = Game_Images()
score = 0
x = 1
def game_start():
global answer, question
int_1 = random.randint(1, 12)
int_2 = random.randint(1, 12)
displayQuestion = "What is "+str(int_1)+ "*" + str(int_2)+"?"
operator = ["*"]
ops = random.choice(operator)
c.create_rectangle(353,0,550,75, fill = "white")
c.create_text(450, 50, font = ("Helvetica", 15), fill="pink", text = displayQuestion)
question = str(int_1) + str(ops) + str(int_2)
answer = int_1 * int_2
def generateQ():
ans = e1.get()
e1.delete(0, END)
if ans == answer:
score += 1
x += 1
print("correct")
print(ans)
print(answer)
else:
print("wrong")
print(ans)
print(answer)
#Buttons show up below the canvas to run commands when pressed
Button(root, text = "Commence Forth",width = 15, command = game_start).place(x=10, y=570)
Button(root, text = "Quit",width = 11, command = quitgame).place(x=800, y=570)
e1 = Entry(root)
e1.pack(padx=30, pady=30)
b=Button(root,text="Enter", width=5, font=("Helvetica", 12), command = generateQ)
b.place(x=550, y=534)
root.mainloop()
Change function generateQ() like this -
def generateQ():
global score,x
ans = e1.get()
e1.delete(0, END)
if int(ans) == int(answer):
score += 1
x += 1
print("correct")
print(ans)
print(answer)
else:
print("wrong")
print(ans)
print(answer)
Use int() so that they are of same data type. And use global score,x because it shows error. You could also write score and x as arguments.

how do I change my counter's speed on tkinter?

I would like to make a money counter with a input box that changes the speed of the counter to display the inputed amount of money per hour, however it's very choppy and doesn't seem to work with different numbers. any advice?
import tkinter as tk
root = tk.Tk()
money = 0
money_per_hour = 1000
root.minsize(500,300)
def monies():
global money_per_hour
box = spinbox.get()
box = int(box)
final = 3600/box
final = round(final)
final = final * 1000
money_per_hour = final
countup()
button = tk.Button(text = "show me the money", fg = "green", command = monies)
button.pack(side = "bottom")
spinbox = tk.Spinbox(from_=0, to=1000000, width=5)
spinbox.pack(side = "bottom")
label = tk.Label(root, text = "$" + str(money), foreground = "green", font = ('calibri', 40, 'bold'))
label.pack()
def countup():
global money
money += 1
label['text'] = "$" + str(money)
root.after(money_per_hour, countup)
root.after(money_per_hour, countup)
root.mainloop()

issues with updating labels from functions in tkinter python 3.8.2

So I've been teaching myself some tkinter to start building some real apps, and my first project is to build an interface for the Courera's all-too-famous Rock-Paper-Scissors-Lizard-Spock game.
Up to now I have all the buttons working fine enough (even though I feel like they are not updating anything if i repeatedly click on the same button without changing choice, as the result of the match never changes) and the result panel also works. that's what's makng me crazy, as far as I can see, the win counters and the computer choice panel follow the same logic and for some reason are not updating when I click a button. any hints?
Thanks already for the patience, and code as follows
import tkinter as tk
import random
from functools import partial
#setting the window early as I had issues and bugs when called after defining functions
window = tk.Tk()
window.geometry('350x200')
#global variables
result= tk.StringVar()
result.set("")
comp = tk.IntVar()
guess = tk.StringVar()
guess.set("")
playerWin = tk.IntVar()
playerWin.set(0)
compWin = tk.IntVar()
compWin.set(0)
#function that handles the computer's play in each game
def compPlay():
global guess, comp
comp.set(random.randrange(0,5))
if comp.get()== 0:
guess.set("Rock")
elif comp.get()== 1:
guess.set("Spock")
elif comp.get() == 2:
guess.set("Paper")
elif comp.get() == 3:
guess.set("Lizard")
elif comp.get() == 4:
guess.set("Scissors")
#function to play human vs computer choices and see who wins
def gameplay(playerNum,compNum):
global result, comp, playerWin, compWin
if playerNum == comp.get():
result.set("It's a tie!")
elif (playerNum - comp.get()) % 5 <= 2:
result.set("Player wins!")
playerWin = playerWin.get() + 1
elif (playerNum - comp.get()) % 5 >= 3:
result.set("Computer wins!")
compWin += compWin.get() + 1
else:
result.set(text = "")
# game title
lblGame= tk.Label(text="Rock, Scissors, Paper, Lizard, Spock").pack()
#frame with the buttons for player choices
playerFrame = tk.Frame(window)
btRock = tk.Button(playerFrame, text = "Rock", width = 15, command = partial(gameplay, 0,compPlay)).pack()
btScissors = tk.Button(playerFrame, text = "Scissors", width = 15, command = partial(gameplay, 1,compPlay)).pack()
btPaper = tk.Button(playerFrame, text = "Paper", width = 15, command = partial(gameplay, 2,compPlay)).pack()
btLizard = tk.Button(playerFrame, text = "Lizard", width = 15, command = partial(gameplay, 3,compPlay)).pack()
btSpock = tk.Button(playerFrame, text = "Spock", width = 15, command = partial(gameplay, 4,compPlay)).pack()
playerFrame.pack(side = tk.LEFT)
#frame with info about the game, as in what the computer chose and the result of the play
compFrame = tk.Frame(window)
lbComp = tk.Label(compFrame, text = "Computer plays:").pack()
lbGuess = tk.Label(compFrame, textvariable = guess, relief = tk.GROOVE, borderwidth = 5, width = 15).pack()
lbRes = tk.Label(compFrame, text = "and the result of the game is").pack()
lbMatch = tk.Label(compFrame, textvariable = result, relief = tk.GROOVE, borderwidth = 5, width = 15).pack()
#mini frames for score keeping
playerFrame = tk.Frame(compFrame, relief = tk.GROOVE, borderwidth = 3)
playerSide = tk.Label(playerFrame, text = "Player points:").pack()
playerScore = tk.Label(playerFrame, textvariable = str(playerWin)).pack()
playerFrame.pack(side = tk.LEFT)
compScoreFrame = tk.Frame(compFrame, relief = tk.GROOVE, borderwidth = 3)
compSide = tk.Label(compScoreFrame, text = "Computer points:").pack()
compScore = tk.Label(compScoreFrame, textvariable = str(compWin)).pack()
compScoreFrame.pack(side = tk.RIGHT)
compFrame.pack(side = tk.RIGHT)
window.mainloop()
I get this error on the console whenever the game should give points to either player:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
return self.func(*args)
File "~/Interactive Python/teste tkinter3.py", line 54, in gameplay
playerWin = playerWin.get() + 1
AttributeError: 'int' object has no attribute 'get'
That's because playWin is a tkinter.Intvar object,you need to change the function gameplay to:
def gameplay(playerNum, compNum):
global result, comp, playerWin, compWin
if playerNum == comp.get():
result.set("It's a tie!")
elif (playerNum - comp.get()) % 5 <= 2:
result.set("Player wins!")
playerWin.set(playerWin.get() + 1)
elif (playerNum - comp.get()) % 5 >= 3:
result.set("Computer wins!")
compWin.set(compWin.get() + 1)
else:
result.set(text="")
There are several problems that are not working properly here:
The Computer plays label field is not refreshing, because you never call the compPlay() function. This function should be called each time the player presses the left-hand button, but this function is unused in the gameplay method. Simply call this function to refresh the computer guess and set the value of a label.
In the gameplay function the compWin and playerWin objects are not ints but tkinter.Intvar so you should set their variables instead of using + and +=. This is the reason for this error.

python - opening an GUI from a list

import random
from tkinter import *
import tkinter as tk
scores = []
score = 0
#introduction
def start():
print(" Welcome to Maths Smash \n")
print("Complete the questions the quickest to get a high score\n")
name = input("What is your name? ")
print("Ok", name, "let's begin!")
#menu
def main():
choice = None
while choice !="0":
print(
"""
Maths Smash
0 - Exit
1 - Easy
2 - Medium
3 - Hard
4 - Extreme
5 - Dashboard
"""
)
choice = input("Choice: ")
print()
#exit
if choice == "0":
print("Good-bye!")
break
#easy
elif choice == "1":
print(" Easy Level ")
print("Complete the test within two minutes to get 10 extra points\n")
easy_level()
#medium
elif choice == "2":
print(" Medium Level ")
print("Complete the test within two minutes to get 10 extra points\n")
medium_level()
#hard
elif choice == "3":
print(" Hard Level ")
print("Complete the test within two minutes to get 10 extra points\n")
hard_level()
#extreme
elif choice == "4":
print(" Extreme Level ")
print("Complete the test within two minutes to get 10 extra points\n")
extreme_level()
#teacher login
elif choice == "5":
print("Dashboard")
dashboard(Frame)
#if the input does not = to choices
else:
print("Sorry but", choice, "isn't a vaild choice.")
class dashboard(Frame):
def __init__(self, master):
super(dashboard, self).__init__(master)
self.grid()
self.main_menu()
def main_menu(self):
#student dashboard button
bttn1 = Button(self, text = "Student",
command=self.student, height = 2, width= 15)
bttn1.grid()
#teacher dashboard button
bttn2 = Button(self, text = "Teacher",
command=self.teacher, height = 2, width= 15)
bttn2.grid()
#exit button
bttn3 = Button(self, text = "Exit",
command=root.destroy, height = 2, width= 15)
bttn3.grid()
self.main_page_buttons = bttn1, bttn2, bttn3 # Save button widgets.
def student(self):
for button in self.main_page_buttons: # Hide the main page Buttons.
button.grid_forget()
#view highscores button
bttn1 = Button(self, text = "Highscores",
command=self.view_scores, height = 2, width= 15)
bttn1.grid()
#print score button
bttn2 = Button(self, text = "Save Score",
command=self.save_score, height = 2, width= 15)
bttn2.grid()
#exit button
bttn3 = Button(self, text = "Exit",
command=root.destroy, height = 2, width= 15)
bttn3.grid()
self.student_page_buttons = bttn1, bttn2, bttn3 # Save button widgets.
def save_score(self):
f = open("Maths Test Score.txt','w")
score = input("What did you score?\n")
f.write(name, score)
f.close()
def teacher(self):
for button in self.main_page_buttons: # Hide the main page Buttons.
button.grid_forget()
#add highscores button
bttn1 = Button(self, text = "Add Highscore",
command=self.add_score, height = 2, width= 15)
bttn1.grid()
#remove score button
bttn2 = Button(self, text = "Remove Highscore",
command=self.remove_score, height = 2, width= 15)
bttn2.grid()
#view highscores
bttn3 = Button(self, text = "View Highscores",
command=self.view_scores, height = 2, width= 15)
bttn3.grid()
#exit button
bttn4 = Button(self, text = "Exit",
command=root.destroy, height = 2, width= 15)
bttn4.grid()
self.teacher_page_buttons = bttn1, bttn2, bttn3, bttn4 # Save button widgets.
def add_score(self):
global scores
score = int(input("What score do you want to add?\n"))
scores.append(score)
def remove_score(self):
global scores
score = int(input("Remove which score?\n"))
if score in scores:
scores.remove(score)
def view_scores(self):
global scores
print("High Scores")
for score in scores:
print(score)
#calling functions
start()
main()
#main for gui
root = Tk()
root.title("Dashboard")
root.geometry("300x170")
app = dashboard(root)
root.mainloop()
Being trying to get this to work for a while now but, what I want to do is open the GUI when the user enters choice '5' but I'm not sure if there is a different way to call a class or something, have looked online for a bit couldn't see any useful examples to help. Any help would be much appreciated, cheers.
I couldn't run code at this moment but I see one mistake.
When dashboard is created it needs parent instance - like root - but in menu() you use Frame which is class name, not instance.
In menu() you will have to create root before you create dashboard, and use root.mainloop() after that.
elif choice == "5":
print("Dashboard")
root = Tk()
root.title("Dashboard")
root.geometry("300x170")
app = dashboard(root)
root.mainloop()
EDIT: full working code.
Because now root is local variable inside main() so in dashboard I use self.master instead of root - see command=self.master.destroy
import random
from tkinter import *
scores = []
score = 0
#introduction
def start():
print(" Welcome to Maths Smash \n")
print("Complete the questions the quickest to get a high score\n")
name = input("What is your name? ")
print("Ok", name, "let's begin!")
#menu
def main():
choice = None
while choice !="0":
print(
"""
Maths Smash
0 - Exit
1 - Easy
2 - Medium
3 - Hard
4 - Extreme
5 - Dashboard
"""
)
choice = input("Choice: ")
print()
#exit
if choice == "0":
print("Good-bye!")
break
#easy
elif choice == "1":
print(" Easy Level ")
print("Complete the test within two minutes to get 10 extra points\n")
easy_level()
#medium
elif choice == "2":
print(" Medium Level ")
print("Complete the test within two minutes to get 10 extra points\n")
medium_level()
#hard
elif choice == "3":
print(" Hard Level ")
print("Complete the test within two minutes to get 10 extra points\n")
hard_level()
#extreme
elif choice == "4":
print(" Extreme Level ")
print("Complete the test within two minutes to get 10 extra points\n")
extreme_level()
#teacher login
elif choice == "5":
print("Dashboard")
root = Tk()
root.title("Dashboard")
root.geometry("300x170")
app = Dashboard(root)
root.mainloop()
#if the input does not = to choices
else:
print("Sorry but", choice, "isn't a vaild choice.")
class Dashboard(Frame):
def __init__(self, master):
super(Dashboard, self).__init__(master)
self.grid()
self.main_menu()
def main_menu(self):
#student dashboard button
bttn1 = Button(self, text = "Student",
command=self.student, height = 2, width= 15)
bttn1.grid()
#teacher dashboard button
bttn2 = Button(self, text = "Teacher",
command=self.teacher, height = 2, width= 15)
bttn2.grid()
#exit button
bttn3 = Button(self, text="Exit",
command=self.master.destroy, height = 2, width= 15)
bttn3.grid()
self.main_page_buttons = bttn1, bttn2, bttn3 # Save button widgets.
def student(self):
for button in self.main_page_buttons: # Hide the main page Buttons.
button.grid_forget()
#view highscores button
bttn1 = Button(self, text = "Highscores",
command=self.view_scores, height = 2, width= 15)
bttn1.grid()
#print score button
bttn2 = Button(self, text = "Save Score",
command=self.save_score, height = 2, width= 15)
bttn2.grid()
#exit button
bttn3 = Button(self, text = "Exit",
command=self.master.destroy, height = 2, width= 15)
bttn3.grid()
self.student_page_buttons = bttn1, bttn2, bttn3 # Save button widgets.
def save_score(self):
f = open("Maths Test Score.txt','w")
score = input("What did you score?\n")
f.write(name, score)
f.close()
def teacher(self):
for button in self.main_page_buttons: # Hide the main page Buttons.
button.grid_forget()
#add highscores button
bttn1 = Button(self, text = "Add Highscore",
command=self.add_score, height = 2, width= 15)
bttn1.grid()
#remove score button
bttn2 = Button(self, text = "Remove Highscore",
command=self.remove_score, height = 2, width= 15)
bttn2.grid()
#view highscores
bttn3 = Button(self, text = "View Highscores",
command=self.view_scores, height = 2, width= 15)
bttn3.grid()
#exit button
bttn4 = Button(self, text = "Exit",
command=self.master.destroy, height = 2, width= 15)
bttn4.grid()
self.teacher_page_buttons = bttn1, bttn2, bttn3, bttn4 # Save button widgets.
def add_score(self):
global scores
score = int(input("What score do you want to add?\n"))
scores.append(score)
def remove_score(self):
global scores
score = int(input("Remove which score?\n"))
if score in scores:
scores.remove(score)
def view_scores(self):
global scores
print("High Scores")
for score in scores:
print(score)
#calling functions
start()
main()

Keep track of score

I am trying to make a quiz that shows the user the name of the state and they have to correctly state the capital. Everything works fine, except for keeping track of the user's score. I have tried to change around the score portion of the code, but nothing is working! I think the problem is somewhere in the nextCapital() function, but then again I could be wrong. I am new to python and all of this is a little overwhelming. I would really appreciate the help!
import tkinter
import random
capitals={"Washington":"Olympia","Oregon":"Salem",\
"California":"Sacramento","Ohio":"Columbus",\
"Nebraska":"Lincoln","Colorado":"Denver",\
"Michigan":"Lansing","Massachusetts":"Boston",\
"Florida":"Tallahassee","Texas":"Austin",\
"Oklahoma":"Oklahoma City","Hawaii":"Honolulu",\
"Alaska":"Juneau","Utah":"Salt Lake City",\
"New Mexico":"Santa Fe","North Dakota":"Bismarck",\
"South Dakota":"Pierre","West Virginia":"Charleston",\
"Virginia":"Richmond","New Jersey":"Trenton",\
"Minnesota":"Saint Paul","Illinois":"Springfield",\
"Indiana":"Indianapolis","Kentucky":"Frankfort",\
"Tennessee":"Nashville","Georgia":"Atlanta",\
"Alabama":"Montgomery","Mississippi":"Jackson",\
"North Carolina":"Raleigh","South Carolina":"Columbia",\
"Maine":"Augusta","Vermont":"Montpelier",\
"New Hampshire":"Concord","Connecticut":"Hartford",\
"Rhode Island":"Providence","Wyoming":"Cheyenne",\
"Montana":"Helena","Kansas":"Topeka",\
"Iowa":"Des Moines","Pennsylvania":"Harrisburg",\
"Maryland":"Annapolis","Missouri":"Jefferson City",\
"Arizona":"Phoenix","Nevada":"Carson City",\
"New York":"Albany","Wisconsin":"Madison",\
"Delaware":"Dover","Idaho":"Boise",\
"Arkansas":"Little Rock","Louisiana":"Baton Rouge"}
score=0
timeleft=30
print("This program will launch a capital quiz game.")
input1 = input("What difficulty would you like to play: easy, normal, or hard?\n")
if input1.lower() == "easy":
seconds = 90
timeleft = seconds
elif input1.lower() == "normal":
seconds = 60
timeleft = seconds
elif input1.lower() == "hard":
seconds = 30
timeleft = seconds
def startGame(event):
#if there's still time left...
if timeleft == seconds:
#start the countdown timer.
countdown()
#run the function to choose the next colour.
nextCapital()
if timeleft == 0:
endlabel = tkinter.Label(root, text="The time is up!\nYour score is: " + str(score) +" out of 50", font=('Helvetica', 12))
endlabel.pack()
e.pack_forget()
#function to choose and display the next colour.
def nextCapital():
#use the globally declared 'score' and 'play' variables above.
global score
global timeleft
#if a game is currently in play...
if timeleft > 0:
#...make the text entry box active.
e.focus_set()
randchoice = random.choice(list(capitals.keys()))
answer = capitals.get(randchoice)
if answer.lower() == randchoice.lower():
score = score+1
#### #this deletes the random choice from the dictionary
#### del capitals[randchoice]
#clear the text entry box.
e.delete(0, tkinter.END)
#this updates the random choice label
label.config(text=str(randchoice))
#update the score.
scoreLabel.config(text="Score: " + str(score))
#a countdown timer function.
def countdown():
#use the globally declared 'play' variable above.
global timeleft
#if a game is in play...
if timeleft > 0:
#decrement the timer.
timeleft -= 1
#update the time left label.
timeLabel.config(text="Time left: " + str(timeleft))
#run the function again after 1 second.
timeLabel.after(1000, countdown)
#create a GUI window.
root = tkinter.Tk()
#set the title.
root.title("Capital Quiz")
#set the size.
root.geometry("500x250")
#add an instructions label.
instructions = tkinter.Label(root, text="Brush up your geography skills!", font=('Helvetica', 12))
instructions.pack()
#add a score label.
scoreLabel = tkinter.Label(root, text="Press enter to start" + str(score), font=('Helvetica', 12))
scoreLabel.pack()
#add a time left label.
timeLabel = tkinter.Label(root, text="Time left: " + str(timeleft), font=('Helvetica', 12))
timeLabel.pack()
#prompt label
promptLabel = tkinter.Label(root, text= "Enter the capital of: ", font=('Helvetica', 12))
promptLabel.pack()
#add a label that will hold print the prompt
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()
#add a text entry box for typing in colours.
e = tkinter.Entry(root)
#run the 'startGame' function when the enter key is pressed.
root.bind('<Return>', startGame)
e.pack()
#set focus on the entry box.
e.focus_set()
#start the GUI
root.mainloop()
randchoice is one of the keys in the capitals dict, i.e. a State.
answer is one of the values in the capitals dict, i.e. a Capital
You then compare the lowercase versions of randchoice and answer and increment the score if they are equal. But clearly they will never be equal (one is a State, one is a Capital). So your score won't be updated properly.
Not an answer, but a bit of advice: eschew all global variables, wrap things into an object with clearly defined, short methods. You will have much easier time working with and reasoning about the code.
Consider this skeleton of a class:
class Quiz(object):
def __init__(self, difficulty, capitals_dict):
self.score = 0
self.capitals = capitals
self.difficulty = ...
self.right_answer = None
def getNextQuestion(self):
# Choose a capital and assign it as the current right answer
...
self.right_answer = ...
return self.right_answer # to show it to user
def checkAnswer(user_answer):
if user_answer == self.right_answer:
self.score = ...
return True
else:
...
def isGameOver(self):
return len(self.capitals) == 0
I guess it's clear enough how to use a class like this, and reasonably clear how to implement it.

Categories