Tkinter while loop guess game - python

# Tkinter guessing game
from tkinter import *
import random
window = Tk()
# Bot Generator
bot = random.randint(1, 20+1)
print(bot)
def submit():
tries = 5
while tries >= 0:
e1 = (int(guessE.get()))
if e1 == bot:
print("You win")
break
elif e1 != bot:
print("Try again")
tries -= 1
break
def clear():
guessE.delete(0, "end")
# Guess Label
guessL = Label(window, text="Guess a number (between 1 and 20}")
guessL.place(x=75, y=50)
# Guess Entry
guessE = Entry(window, width=25, bg="lightgrey")
guessE.place(x=95, y= 80)
# Submit Button
submitBtn = Button(window, width=10, height=2, text="Submit", command=submit)
submitBtn.place(x=85, y=115)
# Clear Button
clearBtn = Button(window, width=10, height=2, text="Clear", command=clear)
clearBtn.place(x=175, y=115)
window.geometry("350x350")
window.resizable(0, 0)
window.attributes("-topmost", True)
window.mainloop()
I am trying to create a guessing game with Tkinter, I have created all the entries and labels, the clear button is working. I am struggling with creating a while loop, I need the program to stop accepting submitted entries once 5 tries have been used. Any ideas on how I can solve this?

Like already mentioned by #Paul Rooney, i also think that a while loop is a bad design for this. However, here is a working example with a global variable and some minor changes (disabling entry and button when 0 tries are reached):
# Tkinter guessing game
from tkinter import *
import random
window = Tk()
# Bot Generator
bot = random.randint(1, 20+1)
print(bot)
# define outside of function to not overwrite each time
tries = 5
def submit():
global tries # to make tries a global variable
while tries > 0: # this matches your tries amount correctly
e1 = (int(guessE.get()))
if e1 == bot:
print("You win")
break
elif e1 != bot:
print("Try again")
tries -= 1
break
# print status, disable the widgets
if tries == 0:
print("No more tries left")
guessE.configure(state="disabled")
submitBtn.configure(state="disabled")
def clear():
guessE.delete(0, "end")
# Guess Label
guessL = Label(window, text="Guess a number (between 1 and 20}")
guessL.place(x=75, y=50)
# Guess Entry
guessE = Entry(window, width=25, bg="lightgrey")
guessE.place(x=95, y= 80)
# Submit Button
submitBtn = Button(window, width=10, height=2, text="Submit", command=submit)
submitBtn.place(x=85, y=115)
# Clear Button
clearBtn = Button(window, width=10, height=2, text="Clear", command=clear)
clearBtn.place(x=175, y=115)
window.geometry("350x350")
window.resizable(0, 0)
window.attributes("-topmost", True)
window.mainloop()

Related

number guessing function in python using tkinter

So ive been trying to create a program of number guessing using tkinter but it isn't working proper like after first attempt it shows 0 attempts while ive declared 3 im attaching the source code here for better understanding the problem i feel is that its not taking attemptsas a global scope so its not being accessed by the other functions
import random
from tkinter import *
random_number = random.randint(0, 999)
root = Tk()
root.geometry('500x500')
root.title("Number guessing game")
label_0 = Label(root, text="Number guessing game", width=20, font=("bold", 20))
label_0.place(x=90, y=53)
label_1 = Label(root, text="Enter number", width=20, font=("bold", 10))
label_1.place(x=80, y=150)
entry_1 = Entry(root)
entry_1.place(x=240, y=150)
def printAttempts(_attempts):
attempt_string = "Attempt left: " + str(_attempts)
label_attempt = Label(root,
text=attempt_string,
width=20,
font=("bold", 20))
label_attempt.place(x=90, y=100)
printAttempts(3)
def printMessage(msg):
_message = Label(root, text=msg, width=50, font=("bold", 10))
_message.place(x=80, y=200)
def onSubmit():
attempts = 3
guessed_number = entry_1.get()
guessed_number = int(guessed_number)
while attempts != 0:
if (guessed_number == random_number):
printMessage("Horray you just got it Right!")
attempts = 0
break
else:
attempts -= 1
printMessage("You got it wrong :(")
if (guessed_number > random_number):
printMessage("Your guess number is greater than lucky number")
else:
printMessage("Your guess number is less than lucky number")
printAttempts(attempts)
continue
if (attempts == 0):
printMessage("No attempts left, try again later")
break
Button(root, text='Submit', width=20, bg='brown', fg='white',
command=onSubmit).place(x=180, y=380)
root.mainloop()
Removing the while loop fixes the problem.
Also have to make the attempts variable global.
Also have to modify the if statements.
Added some print statements for debugging.
comment:
prefer an alias import tkinter as tk to the wildcard from tkinter import *. it is easier to see where functions come from.
This works:
import random
from tkinter import *
attempts = 3
random_number = random.randint(0, 999)
root = Tk()
root.geometry('500x500')
root.title("Number guessing game")
label_0 = Label(root, text="Number guessing game", width=20, font=("bold", 20))
label_0.place(x=90, y=53)
label_1 = Label(root, text="Enter number", width=20, font=("bold", 10))
label_1.place(x=80, y=150)
entry_1 = Entry(root)
entry_1.place(x=240, y=150)
def printAttempts(_attempts):
attempt_string = "Attempt left: " + str(_attempts)
label_attempt = Label(root,
text=attempt_string,
width=20,
font=("bold", 20))
label_attempt.place(x=90, y=100)
printAttempts(3)
def printMessage(msg):
_message = Label(root, text=msg, width=50, font=("bold", 10))
_message.place(x=80, y=200)
def onSubmit():
global attempts
print('attempts', attempts)
guessed_number = entry_1.get()
guessed_number = int(guessed_number)
if attempts != 0:
print('the guess', guessed_number)
print('the random', random_number)
if (guessed_number == random_number):
printMessage("Horray you just got it Right!")
attempts = 0
print(attempts)
else:
print('removing one attempt')
attempts = attempts - 1
printMessage("You got it wrong :(")
if (guessed_number > random_number):
printMessage("Your guess number is greater than lucky number")
print('too high', attempts)
else:
printMessage("Your guess number is less than lucky number")
print('too low', attempts)
if (attempts == 0):
printMessage("No attempts left, try again later")
print('run out', attempts)
printAttempts(attempts)
Button(root, text='Submit', width=20, bg='brown', fg='white',
command=onSubmit).place(x=180, y=380)
root.mainloop()
result:

I want to make a random number guessing game in tkinter

I want a higher or lower game using tkinter in the def tookawhile(): from 0 too 1000 and I want it to go for 3 rounds. When round 3 is over I want it to say "Well done now go user as there is No game" where the text box is locked as the person cant edit it
import tkinter as tk
import random
import time
from tkinter import *
playing_game = False
def to_make_video():
global btn1
text_widget.configure(state='normal')
msg = "People who are watching go hit that subscribe button and"+\
" hit that like button also hit that little bell to turn on"+\
" notifcations"
text_widget.delete("0.0", "end")
text_widget.insert("end", msg)
text_widget.configure(width=25, height=6)
text_widget.configure(state='disabled')
btn1.destroy()
start_game()
def tookawhile():
text_widget.configure(state='normal',height=4)
text_widget.delete("0.0","end")
text_widget.insert("end", "User lets play a game if you arent going to leave\nI have a number between 0 and 1000 in my memory chip can you guess it?")
def whyisthereanapp():
text_widget.configure(state='normal',width=29,height=2)
text_widget.delete("0.0","end")
text_widget.insert("end","Well the creator released it by accident")
text_widget.configure(state='disabled')
btn.destroy()
time.sleep(10)
tookawhile()
def game_won():
# When the button is pressed:
global playing_game
text_widget.configure(state='normal')
playing_game = False
text_widget.delete("0.0", "end")
text_widget.insert("end", "Why aren't you leaving?")
text_widget.configure(width=23, height=1)
text_widget.configure(state='disabled')
btn.destroy()
#btn2 = Button(title="I want to play")
#btn2.pack()
def move_button():
global playing_game
# If the game is over stop moving the button
if not playing_game:
return None
# Pick the next random position for the button
numberx = random.randint(1, 600)
numbery = random.randint(1, 470)
btn.place(x=numberx, y=numbery)
# After 500 milliseconds call `move_button` again
# You can change the value to make it faster/slower
root.after(200, move_button)
def start_game():
# Start the game
global playing_game
btn.config(command=game_won)
playing_game = True
# Start the loop that keeps moving it to new random positions
move_button()
def toplayagame():
text_widget.configure(state='normal')
text_widget.delete("0.0", "end")
text_widget.insert("end", "Well there is no game")
text_widget.configure(width=21)
text_widget.configure(state='disabled')
btn1.destroy()
btn.configure(text='Then why is there an application?',width=25,command=whyisthereanapp,background='Blue',foreground='Yellow',activebackground='Black')
btn.place(x=349, y=470)
def pressed():
global btn1
# Ask the user why they are here
text_widget.configure(state='normal')
text_widget.delete("0.0", "end")
text_widget.insert("end", "Why are you here?")
text_widget.configure(width=17)
text_widget.configure(state='disabled')
btn.place(x=190, y=470)
btn.configure(text="To play a game", width=12, command=toplayagame)
btn1 = tk.Button(root, bd=10, text="To make a video", bg="grey", fg="white",
activebackground="white", activeforeground="black",
height=1, width=15, command=to_make_video)
btn1.place(x=1, y=470)
# Create a window
root = tk.Tk()
root.title("There is no game")
root.geometry("1050x1400")
text_widget = tk.Text(root, height=1, width=10)
text_widget.pack()
text_widget.insert(tk.END, "Hello user")
text_widget.configure(state='disabled')
btn = tk.Button(root, bd=10, text="Hello", activebackground="black",
activeforeground="white", bg="grey", fg="white", height=1,
width=4, command=pressed)
btn.place(x=455, y=470)
# Run tkinter's mainloop
root.mainloop()
ok here is an a simple example that involves the terminal input but you can change it to be the gui input.
`
round = 1
secretNumber = random.randint(1, 1000)
'''text_widget.insert("end",str(secretNumber)) just to know what the number is
for testing'''
for i in range(3):
answer = int(input("Enter guess: "))
if answer < secretNumber:
print("Higher")
elif answer > secretNumber:
print("Lower")
elif answer == secretNumber:
print("Correct")
break
text_widget.config(state=DISABLED)

How do I make btn01 or btn go to a random spot every 4 milliseconds and when you click on it it will stop and do something else?

I want to make any btn go to a random spot every 3 milisecounds, and when you click the random button it will do something else like print Hi and stop the button from moving.
Here is the code:
I tried while a == True: but it keeps frezzing when i press the "To make a video" button and just frezzes for a while
import time
import os
import tkinter as tk
import random
from tkinter import *
from tkinter import messagebox
from tkinter import Button
import math
from tkinter import Text
from tkinter import Grid
from tkinter import Place
#from tkinter import place
window = tk.Tk()
window.title("There is no game")
window.geometry("494x300")
numberx = random.randint(1,200)
numbery = random.randint(1,200)
##def clickedrandom():
## a = False
def toplayagame():
print("Hi")
a = True
def tomakeavideo():
T.delete('1.0', END)
T.insert(tk.END, "People who are watching go hit that subscribe button and hit that like button also hit that little bell to turn on notifcations")
T.configure(width = 25, height=6)
while a == True:
numberx = random.randint(1,200)
numbery = random.randint(1,200)
int(numberx)
int(numbery)
time.sleep(0.3)
btn.place(x = numberx, y = numbery)
def pressed():
T.delete('1.0', END)
T.insert(tk.END, "Why are you here?")
btn.place(x=190, y=200)
T.configure(width = 17, height=1)
btn.configure(text = "To play a game", width=12,command=toplayagame)
btn1= Button(window, bd=10,text="To make a video",activebackground='White',activeforeground='Black',bg='Grey',fg='White',height=1,width=15,state=ACTIVE,command=tomakeavideo)
btn1.pack()
btn1.place(x=1,y=200)
T = tk.Text(window, height=1, width=10)
T.pack()
T.insert(tk.END, "Hello user")
btn = Button(window, bd=10,text="Hello",activebackground='Black',activeforeground='White',bg='Grey',fg='White',height=1,width=4,state=ACTIVE,command=pressed)
btn.pack()
btn.place(x=215, y=200)
window.mainloop()
Use the <tkinter widget>.after(<time>, <function>) like this:
import tkinter as tk
import random
playing_game = False
def to_make_video():
global btn1
msg = "People who are watching go hit that subscribe button and"+\
" hit that like button also hit that little bell to turn on"+\
" notifcations"
text_widget.delete("0.0", "end")
text_widget.insert("end", msg)
text_widget.configure(width=25, height=6)
btn1.destroy()
start_game()
def game_won():
# When the button is pressed:
global playing_game
playing_game = False
text_widget.delete("0.0", "end")
text_widget.insert("end", "Why aren't you leaving?")
text_widget.configure(width=23, height=1)
btn.destroy()
def move_button():
global playing_game
# If the game is over stop moving the button
if not playing_game:
return None
# Pick the next random position for the button
numberx = random.randint(1, 200)
numbery = random.randint(1, 200)
btn.place(x=numberx, y=numbery)
# After 500 milliseconds call `move_button` again
# You can change the value to make it faster/slower
root.after(500, move_button)
def start_game():
# Start the game
global playing_game
btn.config(command=game_won)
playing_game = True
# Start the loop that keeps moving it to new random positions
move_button()
def pressed():
global btn1
# Ask the user why they are here
text_widget.delete("0.0", "end")
text_widget.insert("end", "Why are you here?")
text_widget.configure(width=17)
btn.place(x=190, y=200)
btn.configure(text="To play a game", width=12, command=lambda: None)
btn1 = tk.Button(root, bd=10, text="To make a video", bg="grey", fg="white",
activebackground="white", activeforeground="black",
height=1, width=15, command=to_make_video)
btn1.place(x=1, y=200)
# Create a window
root = tk.Tk()
root.geometry("310x250")
text_widget = tk.Text(root, height=1, width=10)
text_widget.pack()
text_widget.insert(tk.END, "Hello user")
btn = tk.Button(root, bd=10, text="Hello", activebackground="black",
activeforeground="white", bg="grey", fg="white", height=1,
width=4, command=pressed)
btn.place(x=215, y=200)
# Run tkinter's mainloop
root.mainloop()

I'm having an issue with my game in TkInter

So I'm making a game where there is a random number and you have to guess the number while all displayed on an interface. The code was working without the interface (this is the "guess" function) but as soon as I tried to move it into the function when the button is pressed, the game always freezes.
Could someone help me find the problem?
from tkinter import *
import random
import time
root = Tk()
root.title("Mack's totally advanced Number Guesser!")
root.geometry('404x300')
root.resizable(False,False)
root.configure(bg='black')
fontA = 'BigNoodleTitling'
fontSizeA = 20
num = random.randint(1, 100)
# The issue is below
def guess():
correctGuess = False
while (correctGuess == False):
guess = guessEnt.get()
guess = int(guess)
if (guess == num):
correctGuess = True
welcomeLbl.config(text="Correct! Congratulations...")
elif (guess > num):
welcomeLbl.config(text='Err, TOO HIGH. Try Again.')
elif (guess < num):
welcomeLbl.config(text='Errrrrr, TOO LOW. Try Again.')
def start():
instrButton.grid_forget()
startButton.grid_forget()
welcomeLbl.config(text="Guess The Number! (1-100)")
welcomeLbl.grid(pady=30)
guessEnt.grid(row=3, column=0)
guessButton.grid(row=4, column=0, pady=20)
def instructions():
instrButton.grid_forget()
startButton.grid_forget()
welcomeLbl.config(text="So you need instructions ay?")
welcomeLbl.update()
time.sleep(3)
welcomeLbl.config(text="Well, it's quite simple")
welcomeLbl.update()
time.sleep(2)
welcomeLbl.config(text="Just guess the number!")
welcomeLbl.update()
time.sleep(3)
welcomeLbl.config(text="How you say?")
welcomeLbl.update()
time.sleep(2)
welcomeLbl.config(text="Type your guess into the box!")
welcomeLbl.update()
time.sleep(3)
welcomeLbl.config(text="Welcome Random Person")
instrButton.grid(row=3,column=0, sticky=N)
startButton.grid(row=4,column=0, columnspan=1, sticky=E+W, pady=25)
titleLbl = Label(root)
titleLbl['borderwidth'] = (2)
titleLbl['relief'] = ('solid')
titleLbl['text'] = ("Mack's totally advanced Number Guessing Game!")
titleLbl['font'] = (fontA, fontSizeA)
titleLbl.grid(row=0, column=0)
welcomeLbl = Label(root, fg='white', bg='black')
welcomeLbl['text'] = ("Welcome Random Person")
welcomeLbl['font'] = (fontA, 30)
welcomeLbl.grid(row=2, column=0, pady=20)
instrButton = Button(root, command=instructions)
instrButton['text'] = ("Instructions")
instrButton['font'] = (fontA, fontSizeA)
instrButton.grid(row=3,column=0, sticky=N)
startButton = Button(root, fg='red', command=start)
startButton['text'] = ("Start")
startButton['font'] = (fontA, 40)
startButton.grid(row=4,column=0, columnspan=1, sticky=E+W, pady=25)
guessEnt = Entry(root)
guessEnt['font'] = (fontA, fontSizeA)
guessButton = Button(root, command=guess)
guessButton['text'] = ("Guess")
guessButton['font'] = (fontA, 20)
root.mainloop()
Thanks,
Mack.
Remove while (correctGuess == False):. If the answer is incorrect, it will drop into an infinite loop since correctGuess doesn't change in the loop -- it's always False. You can add print(1) in the loop -- you'll see that it can't exit. Remove that line and it should be fine.

Get input in Python tkinter Entry when Button pressed

I am trying to make a 'guess the number' game with Pyhon tkinter but so far I have not been able to retrieve the input from the user.
How can I get the input in entry when b1 is pressed?
I also want to display a lower or higher message as a clue to the player but I am not sure if what I have is right:
import time
import random
import decimal
import tkinter as tk
root = tk.Tk()
randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
guess = 0
def get(entry):
guess = entry.get()
return guess
def main():
b1 = tk.Button(root, text="Guess", command=get)
entry = tk.Entry()
b1.grid(column=1, row=0)
entry.grid(column=0, row=0)
root.mainloop()
print(guess)
if guess < randomnum:
l2 = tk.Label(root, text="Higher!")
l2.grid(column=0, row=2)
elif guess > randomnum:
l3 = tk.Label(root, text="Lower!")
l3.grid(column=0, row=2)
while guess != randomnum:
main()
l4 = tk.Label(root, text="Well guessed")
time.sleep(10)
You could define get inside main, so that you can access the entry widget you created beforehand, like this:
entry = tk.Entry()
def get():
guess = entry.get()
return guess # Replace this with the actual processing.
b1 = tk.Button(root, text="Guess", command=get)
You've assembled random lines of code out of order. For example, the root.mainloop() should only be called once after setting up the code but you're calling it in the middle of main() such that anything after won't execute until Tk is torn down. And the while guess != randomnum: loop has no place in event-driven code. And this, whatever it is, really should be preceded by a comment:
randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
Let's take a simpler, cleaner approach. Rather than holding onto pointers to the the various widgets, let's use their textvariable and command properties to run the show and ignore the widgets once setup. We'll use StringVar and IntVar to handle input and output. And instead of using sleep() which throws off our events, we'll use the after() feature:
import tkinter as tk
from random import randint
def get():
number = guess.get()
if number < random_number:
hint.set("Higher!")
root.after(1000, clear_hint)
elif number > random_number:
hint.set("Lower!")
root.after(1000, clear_hint)
else:
hint.set("Well guessed!")
root.after(5000, setup)
def setup():
global random_number
random_number = randint(1, 100)
guess.set(0)
hint.set("Start Guessing!")
root.after(2000, clear_hint)
def clear_hint():
hint.set("")
root = tk.Tk()
hint = tk.StringVar()
guess = tk.IntVar()
random_number = 0
tk.Entry(textvariable=guess).grid(column=0, row=0)
tk.Button(root, text="Guess", command=get).grid(column=1, row=0)
tk.Label(root, textvariable=hint).grid(column=0, row=1)
setup()
root.mainloop()
Here is a tkinter version on the number guessing game.
while or after are not used!
Program checks for illegal input (empty str or words) and reports error message. It also keeps track of the number of tries required to guess the number and reports success with a big red banner.
I've given more meaningful names to widgets and used pack manager instead of grid.
You can use the button to enter your guess or simply press Return key.
import time
import random
import tkinter as tk
root = tk.Tk()
root.title( "The Number Guessing Game" )
count = guess = 0
label = tk.Label(root, text = "The Number Guessing Game", font = "Helvetica 20 italic")
label.pack(fill = tk.BOTH, expand = True)
def pick_number():
global randomnum
label.config( text = "I am tkinking of a Number", fg = "black" )
randomnum = random.choice( range( 10000 ) )/100
entry.focus_force()
def main_game(guess):
global count
count = count + 1
entry.delete("0", "end")
if guess < randomnum:
label[ "text" ] = "Higher!"
elif guess > randomnum:
label[ "text" ] = "Lower!"
else:
label.config( text = f"CORRECT! You got it in {count} tries", fg = "red" )
root.update()
time.sleep( 4 )
pick_number()
count = 0
def get( ev = None ):
guess = entry.get()
if len( guess ) > 0 and guess.lower() == guess.upper():
guess = float( guess )
main_game( guess )
else:
label[ "text" ] = "MUST be A NUMBER"
entry.delete("0", "end")
entry = tk.Entry(root, font = "Helvetica 15 normal")
entry.pack(fill = tk.BOTH, expand = True)
entry.bind("<Return>", get)
b1 = tk.Button(root, text = "Guess", command = get)
b1.pack(fill = tk.BOTH, expand = True)
pick_number()
root.geometry( "470x110" )
root.minsize( 470, 110 )
root.mainloop()
Correct way to write guess number.
I write a small script for number guessing game in Python in
get_number() function.
Used one widget to update Label instead of duplicating.
I added some extra for number of turns that you entered.
Code modified:
import time
import random
import decimal
import tkinter as tk
root = tk.Tk()
randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
print(randomnum)
WIN = False
GUESS = 0
TURNS = 0
Vars = tk.StringVar(root)
def get_number():
global TURNS
while WIN == False:
Your_guess = entry.get()
if randomnum == float(Your_guess):
guess_message = f"You won!"
l3.configure(text=guess_message)
number_of_turns = f"Number of turns you have used: {TURNS}"
l4.configure(text=number_of_turns)
l4.grid(column=0, row=3, columnspan=3, pady=5)
WIN == True
break
else:
if randomnum > float(Your_guess):
guess_message = f"Your Guess was low, Please enter a higher number"
else:
guess_message = f"your guess was high, please enter a lower number"
l3.configure(text=guess_message)
l3.grid(column=0, row=2, columnspan=3, pady=5)
TURNS +=1
return Your_guess
label = tk.Label(root, text="The Number Guessing Game", font="Helvetica 12 italic")
label.grid(column=0, row=0, columnspan=3, sticky='we')
l2 = tk.Label(root, text='Enter a number between 1 and 100',
fg='white', bg='blue')
l2.grid(row=1, column=0, sticky='we')
entry = tk.Entry(root, width=10, textvariable=Vars)
entry.grid(column=1, row=1, padx=5,sticky='w')
b1 = tk.Button(root, text="Guess", command=get_number)
b1.grid(column=1, row=1, sticky='e', padx=75)
l3 = tk.Label(root, width=40, fg='white', bg='red' )
l4 = tk.Label(root, width=40, fg='white', bg='black' )
root.mainloop()
while guess:
time.sleep(10)
Output for enter floating numbers:
Output after the guess was high:
Output after the guess was low:
Output You won and number of turns:

Categories

Resources