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.
Related
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.
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 1 year ago.
I'm attempting to make a GUI for my text game (similar to a pokemom game)
In summary the code works like:
import random
hp = 100
for i in range (0,4):
element = input("Enter attack: ")
list.append(element)
attack1 = list[0]
attack2 = list[1]
attack3 = list[2]
attack4 = list[3]
while(True):
cmd = input(">")
If cmd.lower() == attack1 ... :
if cmd.lower() == bite:
hp -= 10
Now I tried doing a gui on Tkinter through buttons but it seems I can't get a grasp of it
from tkinter import *
#4 buttons
bite = 0
root = Tk()
def click(hp):
hp -= 10
myLabel = Label(text=f"{hp} hp remaining left.")
myLabel.grid(row = 5, column = 5)
def click2():
bite = 0
hp = 50
hp -= 20
myLabel = Label(text=f"{hp} hp remaining left.")
myLabel.grid(row = 5, column = 5)
bite += 1
myButton = Button(root, text=f"hello {bite}/5", command = click(hp))
myButton2 = Button(root, text=f"Presssss {bite}/5", command = click2)
myButton3 = Button(root, text="Presssss")
myButton4 = Button(root, text="Presssss")
myButton.grid(row = 0, column = 1)
myButton2.grid(row = 1, column = 1)
myButton3.grid(row = 1, column = 2)
myButton4.grid(row = 0, column = 2)
root.mainloop()
And this just presents a constant value "90, 30" due to the variables being included on the function, but whenever I'm trying to put it into an argument like
hp = 100
def click(hp):
hp -= 10
button1 = Button(root, text = "try", command = click(100))
It just returns the value 90, 30 way before the button is clicked. When hp is used as an arg, it is saying undefined.
It does so because click() function is called as soon as window is created.
To prevent it you can use lambda :
myButton = Button(root, text=f"hello {bite}/5", command = lambda: click(hp))
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()
I'm trying to create a Hangman game GUI using Tkinter. I have fully working code apart from several things. I want to create a loop that would restart the game by button press or quit the game by pressing "no".
I also want for these buttons to appear in new window and close the window before.
I've removed not needed parts of the code so you would only see main problem area and main idea. To make it work you just need to type in "b" and then "o":
from Tkinter import *
item = "BOO"
oldString = "-" * (len(item))
blank = "-" * (len(item))
guesses = 10
def start():
winMain.destroy()
mainMenu()
def theWinner():
def end():
root.destroy()
def replay():
root.destroy()
mainMenu()
root = Tk()
root.title("HANGMAN GAME DEMO")
answer = Entry(root)
answer.insert(END, "You Won!!! Play again?")
answer.grid(row = 0, column = 0)
yesB=Button(root, text = "Yes", command = replay)
yesB.grid(row = 1, column = 0)
noB = Button(root, text = "Quit", command = end)
noB.grid(row = 1, column = 1)
root.mainloop()
def mainMenu():
def gameOn():
global guesses
global oldString
newString = ""
i = 0
x = len(item)
hanged = ""
readString = answerIn.get().upper()
winner = 1
if readString not in item:
guesses -= 1
elif readString in item:
while x > 0:
if item[i] != readString:
newString = newString + oldString[i]
elif item[i] == readString:
newString = newString + readString
i +=1
x -=1
oldString = newString
out.config(state=NORMAL)
out.delete(0,END)
out.insert(0,oldString);
out.config(state=DISABLED)
answerIn.delete(0,END)
if oldString == item:
win.destroy()
theWinner()
newString = ""
i=0
x=len(item)
answerIn.delete(0,END)
win = Tk()
win.geometry ("665x480")
win.title("HANGMAN GAME DEMO")
win.configure(background='LightBlue2')
#Display of the word user is trying to guess
guessWord = Entry(win, disabledbackground = "mint cream", disabledforeground = "black", font="helvetica 11 bold", width = 12, border = 2)
guessWord.grid(row=1, column=0, pady = 10, padx = 6, sticky = W)
guessWord.insert(END, "The word is: ")
guessWord.config(state = DISABLED)
#guessWord = Label(win, bg = "mint cream", font="helvetica 10 ", text = "The word you have to guess is: ")
guessWord.grid(row=1, column=0, pady = 10, padx = 9, sticky = W)
out = Entry(win, border = 2, font="helvetica 15 bold", width = 12, disabledforeground = "black", disabledbackground = "gold")
out.insert(0,blank);
out.config(state=DISABLED)
out.grid(row=1, column=0, pady = 10, padx = 200, sticky = W)
#Type in Window
answer = Entry(win, disabledbackground = "mint cream", disabledforeground = "black", font="helvetica 10", width = 21, border = 2)
answer.grid(row=2, column=0, pady = 10, padx = 8, sticky = W)
answer.insert(END,"Please type in the letter: ")
answer.config(state=DISABLED)
answerIn = Entry(win,width = 3, border = 2)
answerIn.focus_set()
answerIn.grid(row=2, column=0, pady = 10, padx = 200, sticky = W)
b = Button(win, text = "Enter",command = gameOn, bg = "chartreuse2", font="helvetica 10 bold",)
b.grid(row=2, column=0, pady = 10, padx = 200)
win.mainloop()
winMain = Tk()
winMain.title("HANGMAN GAME DEMO")
imageLabel = Label(winMain, text = "HELLO!")
imageLabel.pack()
winMain.after(1000, start)
winMain.mainloop()
If I press "no", I get the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1541, in __call__
return self.func(*args)
File "C:/Python27/8.py", line 69, in gameOn
answerIn.delete(0,END)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2509, in delete
self.tk.call(self._w, 'delete', first, last)
TclError: invalid command name ".94412392"
If I press "yes", it does not seem to restart the game from the start. It only lets me enter one character before bringing Win window again.
Where am I going wrong and is there a quick fix for this?
The error is because after destroying the window you want to delete the content in the entry widget. See this part
def mainMenu():
.......
.......
......
if oldString == item:
win.destroy()
theWinner()
# newString = ""
# i=0
# x=len(item)
# answerIn.delete(0,END)
You can see i commented that part you don't need it after closing the window when you do that the error wont pop up again.With regards to the game not starting it thing you should create another function with the same command for for it because
def replay():
root.destroy()
mainMenu()
it isn't working when you call it.I will also suggest you use Toplevel window rather than calling Tk and mainloop more than one.
check this link out [Toplevel documentation][1] .It hard for everyone to debug your code because you are creating several function under another function separate them.
You need to reset oldString when you end a game:
Replace
if oldString == item:
win.destroy()
theWinner()
With
if oldString == item:
win.destroy()
oldString='---'
theWinner()
And it should work (I have tested).
Without trying to solve your issue on your codebase I do recommend to switch the code to be class based, that way you are more in control and can easier keep references which are needed to make some of this gui-stuff work as expected. A bonus will be that you can ditch the globals you have as well.
There is an excellent py2 tkinter doc from where this minimal example is copied just to give an idea of the class based style of coding for gui's, which generally is the prefered way of doing it. You seem to be on py2, however if you're on py3 the docs works as well, you just have to keep track of the minor differences in the imports.
import Tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.quitButton = tk.Button(self, text='Quit', command=self.quit)
self.quitButton.grid()
app = Application()
app.master.title('Sample application')
app.mainloop()
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()