I made a simple 'guess the number' game in Python without any difficulty, so I wanted to challenge myself and take it one step further. I tried to make it in Tkinter, and add in 'guesses' and 'timer' variables.
Here is my code:
import tkinter
import random
guesses = 0
timeleft = 30
numbers = ['1','2','3','4','5','6','7','8','9','10']
numbers2 = []
doTick = True
def startGame(event):
global doTick
doTick = True
number = random.choice(numbers)
numbers.remove(number)
numbers2.append(number)
if timeleft == 30:
countdown()
wrong_guess()
def wrong_guess():
global score
global timeleft
global guesses
if timeleft > 0:
e.focus_set()
if int(e.get()) == int(numbers2[0]):
guesses += 1
guessesLabel.config(text="Guesses: " + str(guesses))
correct_guess()
else:
if int(e.get()) > int(numbers2[0]):
Label.config(text="Your guess is too high!")
guesses += 1
guessesLabel.config(text="Guesses: " + str(guesses))
wrong_guess()
else:
Label.config(text="Your guess is too low!")
guesses += 1
guessesLabel.config(text="Guesses: " + str(guesses))
wrong_guess()
e.delete(0, tkinter.END)
def countdown():
global timeleft
if not doTick:
return
if timeleft > 0:
timeleft -= 1
timeLabel.config(text="Time left:" + str(timeleft))
root.after(1000, countdown)
def correct_guess():
global guesses
global timeleft
global doTick
doTick = False
guessesLabel.config(text="You correctly guessed the number in " + str(guesses) + " guesses!")
timeLabel.config(text="You had " + str(timeleft) + " seconds to spare!")
root = tkinter.Tk()
root.title("Guess the Number")
root.state('zoomed')
timeLabel = tkinter.Label(root, text="", fg="red",font=('Helvetica',25))
timeLabel.pack()
guessesLabel = tkinter.Label(root,text="", fg="green",font=('Helvetica',25))
guessesLabel.pack()
Label = tkinter.Label(root, text="", fg="blue",font=('Helvetica',25))
Label.pack()
e = tkinter.Entry(root)
root.bind('<Return>',startGame)
e.pack()
e.focus_set()
root.mainloop()
My problem is that, when the program runs, the following error message appears:
RecursionError: maximum recursion depth exceeded while calling a Python object
My best guess is that there is something slightly wrong with the def statements, but I am unsure of where this occurs and how this would be fixed.
This is the error message, for those of you who were asking:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
RESTART: C:\Users\Acer_PC\MINCH\Year 10\Computing\python\guess the number.py Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Acer_PC\AppData\Local\Programs\Python\Python35-32\lib\tkinter__init__.py", line 1549, in call
return self.func(*args)