number guessing python tkinter validation - python

previous issue was resolved thanks to you guys can anyone also help me with the validation like if a person clicks check with empty field it prints a message in entry2 like "Field cannot be empty" .Adding code for reference .
from tkinter import *
from tkinter.messagebox import *
import random
root = Tk()
root.title('Number Guessing Game E-project')
root.geometry('500x500')
label1 = Label(root, text= "WELCOME TO NUMBER GUESSING GAME",fg='Maroon',font= ('bold',17))
label2 = Label(root, text= "Enter your guess between 0-999:",font=('Italics',15), fg='Maroon')
label1.grid(row=1 , column=0 ,ipadx=20,pady=10)
label2.grid(row=4 , column=0 ,ipadx=10,pady=10)
player1 = StringVar(root,value="Generate A Random Number First")
entry1 = Entry(root,textvariable=player1,width=30,bd=4)
entry2 = Entry(root,width=30,bd=4)
entry1.grid(row =12 , column= 0 ,ipadx=10,pady=10)
entry2.grid(row =13, column= 0 ,ipadx=10,pady=10)
attempts = 10
chances = StringVar()
chances.set("10 Attempts Remaining")
label4 = Label(root,textvariable=chances,font='Italics')
label4.grid(row=7,column=0 ,ipadx=10,pady=10)
def clear_the_screen():
entry1.delete(0,END)
def random_num_generate():
global random_number , user_guess
random_number = random.randint(0,999)
clear_the_screen()
def player_input():
try:
user_guess = int(entry1.get())
winning_logic(random_number,user_guess)
except ValueError:
entry2.insert(0,"Enter integers only!")
result3 = 'Enter integers only!'
entry2.delete(0, END)
entry2.insert(0, result3)
chances.set(f'{attempts} attempts remaining')
clear_the_screen()
def winning_logic(random_no,player_guess):
global attempts
global chances
attempts -= 1
if attempts < 1:
a = (f'You are out of attempts \n Try again')
showinfo("Sorry", a)
root.destroy()
elif player_guess == random_no:
result1 = 'Bravo! Success!'
entry2.delete(0, END)
entry2.insert(0,result1)
chances.set(f'You Win!')
win = (f'Congrats! You have guessed the correct number !')
showinfo(f'Number Guessing Game', win)
response = askquestion('Number Guessing Game', 'Did you like the game?')
if response == 'yes':
showinfo('Number Guessing Game', "That's Great!!")
else:
showinfo('Number Guessing Game',"So Sad!")
root.destroy()
elif player_guess < random_no and player_guess < 1000:
result2 = 'Guess Higher!'
entry2.delete(0,END)
entry2.insert(0, result2)
chances.set(f'Wrong! {attempts} attempts remaining')
clear_the_screen()
elif player_guess > random_no and player_guess < 1000:
result3 = 'Guess Lower!'
entry2.delete(0,END)
entry2.insert(0, result3)
chances.set(f'Wrong! {attempts} attempts remaining')
clear_the_screen()
elif player_guess > 999:
result3 = 'Invalid Number!'
entry2.delete(0, END)
entry2.insert(0, result3)
chances.set(f'Invalid Number! {attempts} attempts remaining')
clear_the_screen()
button1 = Button(root, text='Generate Random No',fg='white',bg='brown',command=random_num_generate)
button1.grid(row=9, column=0,ipadx=20,pady=8)
button2 = Button(root, text='Clear',fg='white',bg='brown',command=clear_the_screen)
button2.grid(row=18, column=0,ipadx=73,pady=10)
button3 = Button(root, text='Check',fg='white',bg='brown',command=player_input)
button3.grid(row=20, column=0,ipadx=70,pady=8)
root.mainloop()

You can check whether the input is empty in the except block inside player_input():
def player_input():
user_guess = entry1.get()
try:
user_guess = int(user_guess)
winning_logic(random_number, user_guess)
except ValueError:
if user_guess == '':
result3 = 'Field cannot be empty!'
else:
result3 = 'Enter integer only!'
entry2.delete(0, END)
entry2.insert(0, result3)
chances.set(f'{attempts} attempts remaining')
clear_the_screen()

Related

Why is my tkinter window for hangman only appearing after the game has ended?

I am new to python and I've been trying to code a simple hangman game using tkinter. However my tkinter window does not appear when I run the program, like it should. It appears only after the game has ended. i am really confused and cannot for the life of me figure out what is wrong.
Here is my code:
from tkinter import*
from tkinter import messagebox
import random
main = Tk()
main.title("Hangman game")
main.geometry("800x700+120+100")
#-----------------------------------------------------------1
pokusy = 5
spatne_pis = ""
slovo = ""
def vybrat_slovo(slovo):
slovo = random.choice(open("slova_python.txt","r").read().split())
return slovo
spravne_pis = ""
neuhadle = ""
def ukazani(spatne_pis, spravne_pis, slovo):
letters = ""
for letter in spatne_pis:
letters = letters + letter
pism_disp.set(" ".join(letters))
print()
neuhadle = "_"*len(slovo)
for i in range(len(slovo)):
if slovo[i] in spravne_pis:
neuhadle = neuhadle[:i] + slovo[i] + neuhadle[i+1:]
slovo_disp.set(" ".join(neuhadle))
return neuhadle
#----------------------------------------------------------------2
vrchni=Frame(main,width=800,height=50,bd=2,relief="raise")
vrchni.pack(side=TOP,fill=BOTH)
hl_ramec=Frame(main,width=800,height=200,relief="raise")
hl_ramec.pack(side=TOP,fill=BOTH)
klavesnice=LabelFrame(main,text='keys',width=800,height=300,bd=2,relief="raise")
klavesnice.pack(side=TOP,fill=BOTH)
mezera=Frame(main,width=800,height=40,relief="raise")
mezera.pack(side=TOP,fill=BOTH)
dolni=LabelFrame(main,text='comments',width=800,height=100,bd=2,relief="raise")
dolni.pack(side=TOP,fill=BOTH)
hlaska = StringVar()
koment_lb = Label(dolni, textvariable = hlaska, font = ("Arial 22")).grid(padx=90, pady=20)
pomoc_rm=Frame(hl_ramec,width=400,height=300,relief='raise')
pomoc_rm.pack(side=LEFT)
obrazek_ramec=LabelFrame(hl_ramec,text='Hangman - picture',width=400,height=300,bd=2,relief='raise')
obrazek_ramec.pack(side=RIGHT)
status_rm=LabelFrame(pomoc_rm,text='status',width=350,height=80, relief='raise', padx = 10, pady=7)
status_rm.pack(side=TOP)
zbyvajici = IntVar()
pocet_lb = Label(status_rm, textvariable = zbyvajici, font=("Arial 22"))
pocet_lb.pack(side=RIGHT)
zbyvajici = pokusy - len(spatne_pis)
text_lb = Label(status_rm, text="Number of remaining guesses: ", font=("Arial 16"))
text_lb.pack(side=LEFT)
slovo_rm=LabelFrame(pomoc_rm,text='word',width=350,height=100,relief='raise')
slovo_rm.pack(side=TOP)
slovo_disp = StringVar()
slovo_lb = Label(slovo_rm, textvariable = slovo_disp, font = ("Arial 30")).grid(padx=30, pady=7)
zadane_rm=LabelFrame(pomoc_rm,text='wrong entered keys',width=350,height=80,relief='raise')
zadane_rm.pack(side=TOP)
pism_disp = StringVar()
pismena_lb = Label(zadane_rm, textvariable = pism_disp, font = ("Arial 16")).grid(padx=120, pady=15)
#vytvoření malé klávesnice pro uživatele
buttons = [] #seznam jednotlivých kláves
buttons = [
'q','w','e','r','t','y','u','i','o','p',
'a','s','d','f','g','h','j','k','l',
'z','x','c','v','b','n','m'
]
radek=3
sloupec=0
for button in buttons:
command=lambda x=button: select(x)
if button!='Space':
Button(klavesnice,text=button,width=5,font=("arial",14,"bold"),bg='powder blue',command=command,padx=3.5,pady=3.5,bd=5).grid(row=radek,column=sloupec)
if button=='Space':
Button(klavesnice,text=button,command=command).grid(row=5,column=sloupec)
sloupec+=1
if sloupec>9 and radek==3:
sloupec=0
radek+=1
if sloupec>8 and radek==4:
sloupec=0
radek+=1
#---------------------------------------------------------3
uhadle_pis = ""
def hadani(uhadle_pis):
while True:
hlaska = ("Try guessing a letter.")
zadane = input()
zadane = zadane.lower()
if len(zadane) != 1:
hlaska = ("Please enter only one letter")
elif zadane in uhadle_pis:
hlaska = ("You have already guessed that letter, try guessing again. :)")
elif zadane not in "abcdefghijklmnopqrstuvwxyz":
hlaska = ("Please enter a letter of the english alphabet. Entering other characters will not work.")
else:
return zadane
def hrat_znovu():
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
szn = ""
konec_hry = False
slovo = vybrat_slovo(slovo)
while True:
ukazani(spatne_pis,spravne_pis,slovo)
zadane = hadani(spatne_pis + spravne_pis)
if zadane in slovo:
spravne_pis = spravne_pis + zadane
uhadnuto = True
for i in range(len(slovo)):
if slovo[i] not in spravne_pis:
uhadnuto = False
break
if uhadnuto:
konec_hry = True
hlaska = ("Great job! You have succesfully guessed the word! The word was: ",slovo)
else:
spatne_pis = spatne_pis + zadane
if len(spatne_pis) == pokusy:
konec_hry = True
hlaska = ("Sorry, you have been hanged. :(( The word was: ", slovo, ". Try playing again!")
if konec_hry:
if hrat_znovu():
spatne_pis = ""
spravne_pis = ""
konec_hry = False
slovo = vybrat_slovo(slovo)
else:
break
main.mainloop()
The code between the first #--- and second is maybe not important, but i want to include it to be sure. As i said, the tkinter only opens itself if the game has ended and the player does not want to play again. I will be very grateful for any answers :).
def gameloop():
szn = ""
konec_hry = False
slovo = vybrat_slovo(slovo)
while True:
ukazani(spatne_pis, spravne_pis, slovo)
zadane = hadani(spatne_pis + spravne_pis)
if zadane in slovo:
spravne_pis = spravne_pis + zadane
uhadnuto = True
for i in range(len(slovo)):
if slovo[i] not in spravne_pis:
uhadnuto = False
break
if uhadnuto:
konec_hry = True
hlaska = (
"Great job! You have succesfully guessed the word! The word was: ",
slovo)
else:
spatne_pis = spatne_pis + zadane
if len(spatne_pis) == pokusy:
konec_hry = True
hlaska = ("Sorry, you have been hanged. :(( The word was: ", slovo,
". Try playing again!")
if konec_hry:
if hrat_znovu():
spatne_pis = ""
spravne_pis = ""
konec_hry = False
slovo = vybrat_slovo(slovo)
else:
break
main.after(1000,gameloop)
main.mainloop()

TypeError: '>=' not supported between instances of 'str' and 'int'? [duplicate]

I am trying to make a guess game program where you have to guess a number between 0-100 on a GUI using Tkinter, and it also counts your amount of attempts but I get this error on line 25:
'<' is not supported between instances of str and int.
What can I do to solve this issue? This code would work on a command line but not when I have attempted to translate it into a GUI. I am also not sure if the code even works.
My updated code so far is:
import random
from tkinter import *
#need to count how many attempts you made
window = Tk()
window.title("Number guessing game")
window.geometry('350x200')
lbl = Label(window, text="Enter a number here from 1-100: ")
lbl.grid(column=0,row=0)
guess_var = IntVar(window)
txt = Entry(window, textvariable=guess_var)
txt= Entry(window, width=10)
txt.grid(column=1,row=0)
numguess = 0
secret_num = random.randint(1, 100)
def clicked():
if guess < 0:
lbl2.configure(text ="Please enter a sensible number.")
if guess > 100:
lbl2.configure(text ="Please enter a sensible number.")
if guess == secret_num:
lbl2.configure(text ="You guessed correctly.")
lbl3.confgure(text=numguess)
elif guess < secret_num:
numguess = numguess + 1
lbl2.configure(text ="higher!")
lbl = Label(window, text="Enter a number here from 1-100: ")
else:
numguess = numguess + 1
lbl2.configure(text ="lower!")
lbl = Label(window, text="Enter a number here form 1-100")
lbl2 = Label(window,text = " ")
lbl2.grid(column=1, row=2)
lbl3 = Label(window,text = " ")
lbl3.grid(column=1, row=3)
btn = Button(window, text="Enter", command=clicked)
guess = int(txt.get())
btn.grid(column=3, row=0)
window.mainloop()
guess = txt.get()
returns a string value. To be able to perform comparisons with integers, you need to convert guess from a string to an integer, i.e.:
guess = int(txt.get())
To be safe, you may want to handle the case where the user inputs something which cannot be converted to a integer; how to do this depends on the design of your problem - you should consider validating the user input.
One way to do this could be by using IntVar, e.g.:
guess_var = IntVar(window)
txt = Entry(window, textvariable=guess_var)
txt.grid(column=1,row=0)
numguess = 0
secret_num = random.randint(1, 100)
guess = guess_var.get()
Note that if you want to use the numguess global variable inside your clicked function, you need to declare global numguess in your function definition, e.g.:
def clicked():
global numguess

Is there a way to not use global variables in my code?

I am relatively new to Python so please bear with the inefficiency of my code. This is one of my first Tkinter applications and it is quite a simple one. It is a code guessing game where the user tries to guess a randomly generated 4 digit code. The code currently prints the randomly generated number so that it is easier to see if the code is working. But is there a way to not use global variables in this code. Also, it would be helpful if I was told how to make my code efficient. Thanks in advance. Code:
import random
import tkinter as tk
number_of_tries = 0
def tries():
global number_of_tries
number_of_tries += 1
comment.configure(state="normal")
comment.delete(0, "end")
comment.insert(0, "Not quite! Keep trying!")
comment.configure(state="disabled")
if str(guess) == str(random_number):
comment.configure(state="normal")
comment.delete(0, "end")
comment.insert(0, "You guessed it in " + str(number_of_tries) + " tries!")
comment.configure(state="disabled")
guess_entry.configure(state="disabled")
go.configure(state="disabled")
def character_check():
global guess
guess = guess_entry.get()
if len(guess) != 4:
comment.configure(state="normal")
comment.delete(0, "end")
comment.insert(0, "Guess must be 4 digits! ")
comment.configure(state="disabled")
else:
for char in guess:
if char.isalpha():
comment.configure(state="normal")
comment.delete(0, "end")
comment.insert(0, "Guess must only include integers! ")
comment.configure(state="disabled")
else:
digit_check()
def digit_check():
global guess
guess = guess_entry.get()
for i in range(0, 4):
if str(guess)[i] == str(random_number)[i]:
digits[i] = str(guess)[i]
digit_display.configure(state="normal")
digit_display.delete(0, "end")
digit_display.insert(0, digits)
digit_display.configure(state="disabled")
elif str(guess)[i] != str(random_number)[i]:
digits[i] = "?"
digit_display.configure(state="normal")
digit_display.delete(0, "end")
digit_display.insert(0, digits)
digit_display.configure(state="disabled")
def initialise():
global number_of_tries, digits
global random_number
digits = ["?"] * 4
random_number = random.randrange(1000, 9999)
number_of_tries = 0
digit_display.configure(state="normal")
comment.configure(state="normal")
digit_display.delete(0, "end")
digit_display.insert(0, digits)
comment.delete(0, "end")
comment.insert(0, "Good luck!")
digit_display.configure(state="disabled")
comment.configure(state="disabled")
guess_entry.configure(state="normal")
go.configure(state="normal")
print(random_number)
screen = tk.Tk()
screen.geometry("400x400")
screen.title("Code Crunchers")
heading = tk.Label(text="Welcome to Code Crunchers!", font="Montserrat 15")
heading.place(relx=0.5, rely=0.1, anchor="center")
instruction_1 = tk.Label(text="Enter your guess below: ", font="Montserrat 10")
instruction_1.place(relx=0.5, rely=0.2, anchor="center")
guess_entry = tk.Entry(screen, width=4)
guess_entry.place(relx=0.5, rely=0.25, anchor="center")
go = tk.Button(text="Go", font="Montserrat 10", command=lambda: [character_check(), tries()])
go.place(relx=0.6, rely=0.27, anchor="center")
instruction_2 = tk.Label(text="Digits correct: ", font="Montserrat 10")
instruction_2.place(relx=0.5, rely=0.35, anchor="center")
digit_display = tk.Entry(screen, width=10)
digit_display.place(relx=0.5, rely=0.4, anchor="center")
comment = tk.Entry(screen, width=40)
comment.place(relx=0.5, rely=0.45, anchor="center")
restart = tk.Button(text="Restart", font="Montserrat 10", command=lambda: initialise())
restart.place(relx=0.5, rely=0.55, anchor="center")
initialise()
screen.mainloop()
What I would do is simply display the number of tries to the user and then read from that object to see the amount of tries. If you do not want to display it to the user you can always hide it so it does not display. If you do not want to have it on your GUI at all you should then pass this variable around as arguments in your functions.

How to save progress to a text file?

I am trying to save progress as a text file. I've tried pickle but it didn't work.
Here's the code; I want to ask at the start if they want to load or start a new game and at any point of the guessing process if they want to save their progress.
# Username and password system to get into the puzzle
Username = []
Password = []
while Username != "Username":
Username = input("Please enter your username: ")
while Password != "Password":
Password = input("Please enter your password: ")
#Import Modules
import tkinter as tkr
import string
import random
import os
import time
from collections import OrderedDict
while True:
#Define Root From tkinter
root = tkr.Tk()
root.configure(background="white")
root.configure(highlightbackground="grey")
root.iconbitmap("PuzzleIcon.ico")
#Inputs for title etc...
Title = input("Please enter the Title of your puzzle: ")
Phrase = input("Please enter the phrase you would like to be encoded: ").upper()
giveaways = str(input("Please enter the letters you want to giveaway with no spaces: ")).upper()
giveaways = giveaways + " "
giveaways = "".join(OrderedDict.fromkeys(giveaways))
root.title(Title)
#Define alphabet and numbers
Alphabet = list(string.ascii_uppercase)
Numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
random.shuffle(Numbers)
# Specifies the numbers to put under the phrase
AlphabetNumbersToDisplay = []
Numbers.append(" ")
Alphabet.append(" ")
for letter in Phrase:
n = 0
found = False
while n < len(Alphabet) and found == False:
if letter == Alphabet[n]:
AlphabetNumbersToDisplay.append(Numbers[n])
found = True
n = n + 1
# Defines the tkinter window
def tkinterDisplay():
for i in range (0, len(Alphabet)):
tkr.Label(root, text=Alphabet[i], fg="black", bg="white", width=3).grid(row=0, column=i)
for i in range (0, len(Numbers)):
if Alphabet[i] in giveaways:
tkr.Label(root, text=Numbers[i], fg="black", bg="white", width=3).grid(row=1, column=i)
else:
tkr.Label(root, text= "__", fg="black", bg="white", width=3).grid(row=1, column=i)
tkr.Label(root, text=" ", fg = "white",bg="white").grid(row=2)
for i in range(0, len(Phrase)):
if Phrase[i] in giveaways:
tkr.Label(root, text=Phrase[i], fg= "black", bg="white", width = 3).grid(row = 3, column =i)
else:
tkr.Label(root, text="__", fg= "black", bg="white", width = 3).grid(row = 3, column =i)
for i in range(0, len(AlphabetNumbersToDisplay)):
tkr.Label(root, text=AlphabetNumbersToDisplay[i], fg= "black", bg="white", width = 3).grid(row = 4, column =i)
winMessage = "Well done! You Won!".upper()
for i in range(0, len(winMessage)):
if len(giveaways) == 27:
tkr.Label(root, text=" ", fg = "white",bg="white").grid(row=5)
tkr.Label(root, text=winMessage[i], fg="red", bg="white", width = 3).grid(row = 6, column=i)
# Guessing system for the program
def Guessing():
tkinterDisplay()
while True:
try:
GuessNum = int(input("Please enter the number of your guess: "))
break
except ValueError:
print("Your answer must be a number!")
while True:
try:
GuessLetter = str(input("Please enter the letter you want to guess: ")).upper()
break
except ValueError:
print("Your answer must be a letter!")
foundMatch = False
for i in range(0, len(Alphabet)):
if Alphabet[i] == GuessLetter and Numbers[i] == GuessNum:
global giveaways
foundMatch = True
giveaways = giveaways + Alphabet[i]
if foundMatch == False:
print("They do not match, try again!")
elif foundMatch == True and len(giveaways) < 27:
print("Well done! Keep going!")
while len(giveaways) < 27:
Guessing()
tkinterDisplay()
def Clear():
os.system("cls")
if len(giveaways) == 27:
tkinterDisplay()
print("Well done! You won! The phrase you guessed was: " + Phrase)
Restart = input("Would you like to play again? (Y/N): ").upper()
if Restart == "N":
break
elif Restart == "Y":
print("Restarting Puzzle...")
time.sleep(.1500)
root.destroy()
Clear()
continue
root.mainloop()
This is a very broad question. Building a 'save' option may well be as much work as the rest of the game again. You need to consider the following:
What data is needed to fully define the state of the game at any given point (this is what goes in the text file)
What logic is needed to reconstruct a game in a saved state (you'll need to write new code for this)
How and when to give your users the chance to load/save (this affects the gameplay experience)

Creating a Tkinter math Quiz

I am learning python and am having trouble getting this program to work correctly.
from Tkinter import*
import time
import tkMessageBox
import random
def Questions():
number1 = random.randrange(1,25,1)
number2 = random.randrange(1,50,2)
answer = number1 + number2
prompt = ("Add " + str(number1) + " and " + str(number2))
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
return answer
def start():
global count_flag
Questions()
count_flag = True
count = 0.0
while True:
if count_flag == False:
break
# put the count value into the label
label['text'] = str(count)
# wait for 0.1 seconds
time.sleep(0.1)
# needed with time.sleep()
root.update()
# increase count
count += 0.1
def Submit(answer, entryWidget):
""" Display the Entry text value. """
global count_flag
count_flag = False
print answer
if entryWidget.get().strip() == "":
tkMessageBox.showerror("Tkinter Entry Widget", "Please enter a number.")
if int(answer) != entryWidget.get().strip():
tkMessageBox.showinfo("Answer", "INCORRECT!")
else:
tkMessageBox.showinfo("Answer", "CORRECT!")
# create a Tkinter window
root = Tk()
root.title("Math Quiz")
root["padx"] = 40
root["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Answer:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
#directions
directions = ('Click start to begin. You will be asked a series of questions like the one below.')
instructions = Label(root, text=directions, width=len(directions), bg='orange')
instructions.pack()
# this will be a global flag
count_flag = True
answer = Questions()
Sub = lambda: Submit(answer, entryWidget)
# create needed widgets
label = Label(root, text='0.0')
btn_submit = Button(root, text="Submit", command = Sub)
btn_start = Button(root, text="Start", command = start)
btn_submit.pack()
btn_start.pack()
label.pack()
# start the event loop
root.mainloop()
It just says "INCORRECT!" every time I push submit regardless of what I enter into the text box. Any suggestions would be appreciated. Thanks, Scott
Left side is an integer, right side is a string, so it's always False:
int(answer) != entryWidget.get().strip()
You can try:
int(answer) != int(entryWidget.get().strip())

Categories