python - opening an GUI from a list - python

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()

Related

Jumping between functions in tkinter

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()

how to create a scoring system

I'm trying to make my scoring system work. it keeps forgetting after I have changed the score once I go back into the class as it is set as 0. How would I change this so the score changes as appropriate?
code:
import random
from tkinter import *
class TimesTableGUI:
def __init__(self, parent, score = 0):
self.score = score
#chooses a random number
num1 = random.randint(1,10)
num2 = random.randint(1,10)
self.answer = num1 * num2
#making labels
entry_label = Label(parent, text = str(num1) + " * " + str(num2))
entry_label.grid(row = 0, column = 0)
self.e1 = Entry(parent, width = 5)
self.e1.grid(row = 0, column = 1)
b1 = Button(parent, text = "Check Answer", command = self.check_answer)
b1.grid(row = 1, column = 0)
b2 = Button(parent, text = "Next", command = self.new_question)
b2.grid(row = 1, column = 1)
self.b1_output = Label(parent, text = self.score)
self.b1_output.grid(row = 2, column = 0)
def check_answer(self): #callback for Check Answer button
#check if users gets correct answer
f = int(self.e1.get())
if f == self.answer:
self.score +=1
self.b1_output.configure(text = self.score)
else:
self.b1_output.configure(text = self.score)
def new_question(self): #callback for Next button to next question
self.b1_output.configure(text = " ")
radiobuttons = TimesTableGUI(root) #restarts the class for new question
if __name__ == "__main__":
root = Tk()
root.title("Task 3")
radiobuttons = TimesTableGUI(root)
root.mainloop()
Try this:
import random
from tkinter import *
class TimesTableGUI:
def __init__(self, parent, score=0):
self.score = score
self.master = parent
self.ask_new_question()
self.b1_output = Label(parent, text="Score = %i" % self.score)
self.b1_output.grid(row=2, column=1)
def ask_new_question(self):
self.question_frame = Frame(self.master)
self.question_frame.grid(row=1, column=1)
#chooses a random number
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
self.answer = num1 * num2
#making labels
entry_label = Label(self.question_frame, text="%i*%i" % (num1, num2))
entry_label.grid(row=0, column=0)
self.e1 = Entry(self.question_frame, width=5)
self.e1.grid(row=0, column=1)
self.check_answer_btn = Button(self.question_frame, text="Check Answer",
command=self.check_answer)
self.check_answer_btn.grid(row=1, column=0)
b2 = Button(self.question_frame, text="Next",
command=self.new_question)
b2.grid(row=1, column=1)
def check_answer(self):
user_answer = int(self.e1.get())
if user_answer == self.answer:
self.score += 1
self.b1_output.configure(text="Score = %i" % self.score)
# So the user can't submit more than 1 correct answer
self.check_answer_btn.config(state="disabled")
def new_question(self):
# Remove the frame (and all of its children)
self.question_frame.destroy()
# Display the new question
self.ask_new_question()
if __name__ == "__main__":
root = Tk()
root.title("Task 3")
radiobuttons = TimesTableGUI(root)
root.mainloop()
I moved all of the widgets that are for the question inside a frame. The frame gets destroyed and recreated each time a new question needs to be displayed. I also made sure the user can't just keep clicking on Check Answer after they got the correct answer already (for that question).
The problem is that when you you call radiobuttons = TimesTableGUI(root) score is getting reset too.
Quick solution: pass score when you call radiobuttons = TimesTableGUI(root, score=self.score) in new_question
Better solution: create a method that reset GUI without reinitialize the entire class.

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.

tkinter: How to change labels inside the program itself

I was asked to edit my code so I decided to include the entire calculator script
from tkinter import *
global choice
choice = 0
#Program
def calculate(*event):
if choice == 1:
try:
add1 = ccalc1.get()
add2 = ccalc2.get()
except:
no = Label(app, text="You must use a number").grid(row=0, column=0)
answ = add1 + add2
answer = Label(app, text = answ).grid(row=1, column=0)
elif choice == 2:
try:
sub1 = ccalc1.get()
sub2 = ccalc2.get()
except:
no = Label(app, text="You must use a number").grid(row=1, column=0)
answ = sub1 - sub2
answer = Label(app, text = answ).grid(row=1, column=0)
def choice2():
global choice
choice = 2
#End Program
#GUI
#Window Info
calc = Tk()
calc.title("Calculator")
calc.geometry("200x140")
#End Window Info
#Build Window
app = Frame(calc)
app.grid()
ccalc1 = IntVar()
ccalc2 = IntVar()
#Widgets
if choice == 0:
welcome = Label(app, text="Select a choice")
elif choice == 2:
welcome.config(text="Subtraction")
calcbox1 = Entry(app,textvariable=ccalc1)
calcbox2 = Entry(app,textvariable=ccalc2)
submit = Button(app, text="CALCULATE", command = calculate)
welcome.grid(row=0,column=0)
calcbox1.grid(row=2, column=0)
calcbox2.grid(row=3, column=0)
submit.grid(row=4, column=0)
calc.bind('<Return>', calculate)
#End Widgets
#Menu
menu=Menu(calc)
#Operations
filemenu = Menu(menu,tearoff=0)
filemenu.add_command(label="Subtract", command = choice2)
menu.add_cascade(label="Operations",menu=filemenu)
calc.config(menu=menu)
calc.mainloop()
#End GUI
what wrong is that the welcome label text wont change accordingly.
Update: I included the entire calculator code
Any help is appreciated.
It's hard to understand what you expect to happen. For example, look at this code:
#Widgets
if choice == 0:
welcome = Label(app, text="Select a choice")
elif choice == 2:
welcome.config(text="Subtraction")
This code will only ever execute once, and choice will always be zero since that's what you initialize it to. It executes once because it's not in a function and not in a loop, so as python parses the code it will run it and move to the next line. That block of text will never be processed a second time.
If you want the label to change when the user selects a menu item, you'll need to execute that code inside the choice2 function:
def choice2():
global choice
choice = 2
welcome.config(text="Subtraction")

Python Tkinter: Loop The Computer's Turn A Certain Amount of Times

I'm writing a program for a dice game (Pig). In the game, the player will roll a d6 until they decide to hold their score (passing to the computer) or until they roll a 1, which will automatically make it the computer's turn.
The issue I'm having is that I need the function for the computer's turn to loop ten times. I want the computer to roll the die ten times, where it will either roll a one and pass back to the player or it will hold after ten rolls. How do I get the computer to roll the die ten times without using a loop inside of Tk?
Here's the code:
from Tkinter import *
from random import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.headerFont = ("courier new", "16", "bold")
self.title("Pig, The Dice Game")
self.headers()
self.rollDie()
def headers(self):
Label(self, text = "Instructions", font = self.headerFont).grid(columnspan = 4)
Label(self, text = "Text", font = self.headerFont).grid(row = 1, columnspan = 4)
Label(self).grid(row = 1, columnspan = 4)
Label(self, text = "The Game of Pig", font = self.headerFont).grid(row = 2, columnspan = 4)
def rollDie(self):
self.btnRoll = Button(self, text = "Roll The Die")
self.btnRoll["state"] = 'active'
self.btnRoll.grid(row = 3, columnspan = 4)
self.btnRoll["command"] = self.playerTurn
self.btnHold = Button(self, text = "Hold")
self.btnHold["state"]= 'active'
self.btnHold.grid(row = 4, columnspan = 4)
self.btnHold["command"] = self.compTurn
self.btnPass = Button(self, text = "Pass")
self.btnPass.grid(row = 5, columnspan = 4)
self.btnPass["command"] = self.compTurn
Label(self, text = "You Rolled:").grid(row = 6, column = 0)
self.lblYouRolled = Label(self, bg = "#fff", anchor = "w", relief = "groove")
self.lblYouRolled.grid(row = 6, column = 1, columnspan = 1, sticky = "we")
Label(self, text = "Options:").grid(row = 7, column = 0)
self.lblOptions = Label(self, bg = "#fff", anchor = "w", relief = "groove")
self.lblOptions.grid(row = 7, column = 1, sticky = "we")
Label(self, text = "Player One Turn Score:").grid(row = 8, column = 0)
self.lblPlayerOneTurnScore = Label(self, bg = "#fff", anchor = "w", relief = "groove")
self.lblPlayerOneTurnScore.grid(row = 8, column = 1, sticky = "we")
def playerTurn(self):
self.oneTurnTotal = [0]
self.oneRoll = randint(1,6)
self.btnHold["state"] = 'active'
self.lblYouRolled["text"] = self.oneRoll
if self.oneRoll != 1:
self.oneTurnTotal.append(self.oneRoll)
self.lblOptions["text"] = "Roll again, or hold and pass the dice to Player Two."
else:
self.lblOptions["text"] = "You rolled a 1! Click 'Pass' to pass your turn to the computer."
self.oneTurnTotal = [0]
self.btnRoll["state"] = 'disabled'
self.btnHold["state"] = 'disabled'
def calculatePlayerOneTurnScore(self):
turnScore = sum(self.oneTurnTotal)
self.lblPlayerOneTurnScore["text"] = turnScore
def compTurn(self):
self.compTurnTotal = [0]
self.compRoll = randint(1,6)
self.lblYouRolled["text"] = self.compRoll
if self.compRoll != 1:
self.compTurnTotal.append(self.compRoll)
self.lblOptions["text"] = "The computer will roll again."
else:
self.lblOptions["text"] = "The computer rolled a 1! Its turn has ended."
self.compTurnTotal = [0]
self.btnRoll["state"] = 'active'
def calculatePlayerTwoTurnScore(self):
turnScore = sum(self.twoTurnTotal)
self.lblPlayerTwoTurnScore["text"] = turnScore
def main():
app = App()
app.mainloop()
if __name__ == "__main__":
main()
You could make the dicerolling a toplevel widget and then have your root "wait_window" for the rolling widget to complete. Create a function inside the toplevel widget that generates the roll and call it ten times
EXAMPLE
from Tkinter import *
yourscorevalue=12
cpuscorevalue=10
class dice:
def __init__(self,parent):
rollcount=0
top=self.top=Toplevel(parent)
while 1:
roll=self.diceroll()
rollcount+=1
if rollcount==10 or roll==1:
break
def diceroll(self):
#Random Dice Roll code
class dicegame:
def __init__(self):
self.root=Tk()
self.root.title('Dicerolling Game')
Label(self.root, text='Your Score').grid(column=0,row=0,sticky='ew')
Label(self.root, text=yourscorevalue, background='black',foreground='red').grid(column=1,row=0,sticky='ew')
Label(self.root, text='Computer Score').grid(column=0,row=1,sticky='ew')
Label(self.root, text=cpuscorevalue, background='black',foreground='red').grid(column=1,row=1,sticky='ew')
b=Button(self.root, text='Roll The Dice', command=self.roll).grid(column=0,row=2,sticky='ew')
c=Button(self.root, text="Done", command=self.root.destroy).grid(column=1,row=2,sticky='ew')
mainloop()
def roll(self):
d=dice(self.root)
self.root.wait_window(d.top)

Categories