Guess the number with Tkinter, Python3 - python

here is my code:
from tkinter import *
import random
def initGame():
window = Tk()
window.title("Guess the number game")
lbl = Label(window, text="Guess number from 1 to 100. Insert how many tries would you like to have: ", font=("",16))
lbl.grid(column=0, row=0)
txt = Entry(window, width=10)
txt.grid(column=0, row=1)
txt.focus() #place cursor auto
def clicked():
number_dirty = txt.get()
tries = int(number_dirty)
playGame(tries)
btn = Button(window, text="Start", command=clicked)
btn.grid(column=0, row=2)
window.geometry('800x600')
window.mainloop()
def playGame(tries):
number_of_tries = int(tries)
number = random.randint(1,100)
higher_notification = "Number is HIGHER"
lower_notification = "Number is LOWER"
game_window = Tk()
game_window.title("Game Window")
lbl = Label(game_window, text="Guess numbers between 1 and 100, you have %s tries !" %(number_of_tries), font=("",14))
lbl.grid(column=0, row=0)
txt = Entry(game_window, width=10)
txt.grid(column=0, row=1)
txt.focus()
print(number)
print(number_of_tries)
def clicked():
user_input = txt.get()
compareNumbers(number, user_input)
btn_try = Button(game_window, text="Try!", command="clicked")
btn_try.grid(column=0, row=2)
def compareNumbers(number, user_input):
if user_input == number:
messagebox.showinfo('You have won!', 'Right! the number was %s ' %(number))
else:
if user_input > number:
lbl.configure(lower_notification)
number_of_tries -1
else:
lbl.configure(higher_notification)
number_of_tries -1
game_window.geometry('600x600')
game_window.mainloop()
initGame()
On the first screen (initGame) everything works fine, when I click the button I do indeed get the second screen, which displays all objects normally. When I click the button in the game screen I get no feedback at all, nothing happens.
What am I missing?
Thank you very much !

The problem is in this line:
btn_try = Button(game_window, text="Try!", command="clicked")
Note that the command "clicked" is inside quotaions marks and therefor a string and not the method you tried to reference. What you want is:
btn_try = Button(game_window, text="Try!", command=clicked)

Related

The if condition does not work as expected in Tkinter

I've been having some troubles with this code as the if condition cannot be true and always executes the else condition instead.
can you help
`
from tkinter import *
root = Tk()
entry_1 =Entry(root, width = 20)
entry_1.pack()
entry_1.insert(0, "Choose Your Number ")
def m():
answer = entry_1.get().strip()
if answer == 5 :
mylabel = Label(root, text = "YOU WIN!")
mylabel.pack()
else :
mylabel = Label(root, text = "YOU LOST!")
mylabel.pack()
mybutton = Button(root, text = 'PLAY', command = m)
mybutton.pack()
root.mainloop()
Thanks
Any user input is a string, so you need to convert to an Integer.
Try this code:
from tkinter import *
root = Tk()
entry_1 =Entry(root, width = 20)
entry_1.pack()
entry_1.insert(0, "Choose Your Number ")
def m():
answer = int(entry_1.get().strip())
if answer == 5 :
mylabel = Label(root, text = "YOU WIN!")
mylabel.pack()
else :
mylabel = Label(root, text = "YOU LOST!")
mylabel.pack()
mybutton = Button(root, text = 'PLAY', command = m)
mybutton.pack()
root.mainloop()

How do I get the values assigned to the Correct and Total numbers to update when the user inputs their answer?

I have a Python file that when run, opens a window for simple addition practice. It asks the user for their input, and if the total is correct will output "Right!" and "Oops!" for incorrect. Below all of this is a counter that keeps track of the correct number out of the total. However, at the moment, those numbers both remain zero when user enters their input. What kind of changes would need to be made under the ClicktheButton1 function in order to get this program properly functioning? Thanks.
The output would end up looking like "2 out 4 correct" in the window, updating after each new problem is solved.
from tkinter import *
import random as rn
window = Tk()
window.geometry('350x350')
window.title("C200")
x = rn.randint(0,100)
y = rn.randint(0,100)
correct, incorrect = 0,0
myLabel = Label(window, text="{0}+{1}=".format(x,y), font=("Arial Bold", 15))
myLabel.grid(column=0, row=0)
myLable2 = Label(window, text = "",font=("Arial Bold", 15))
myLable2.grid(column=0, row=5)
mylabel3 = Label(window,text = "0 out of 0 correct",font=("Arial Bold", 15))
mylabel3.grid(column=0, row=10)
mytxt = Entry(window, width=12)
mytxt.grid(column=1,row=0)
def ClicktheButton1():
global x
global y
global correct
global incorrect
myguess = int(mytxt.get())
if x + y == myguess:
myLable2.configure(text = "Right!")
correct += 1
else:
myLable2.configure(text = "Oops!")
incorrect += 1
x = rn.randint(0,100)
y = rn.randint(0,100)
mytxt.focus()
mytxt.delete(0,END)
myLabel.configure(text = "{0}+{1}=".format(x,y))
btn1 = Button(window, text="check", command = ClicktheButton1)
btn1.grid(column=0, row=7)
def ClicktheButton2():
window.destroy()
btn1 = Button(window, text="Quit", command = ClicktheButton2)
btn1.grid(column=400, row=400)
window.mainloop()
You have to change text in mylabel3 in the same why as you change text in myLabel - and even in the same place. I don't know why you have problem with this.
myLabel.configure(text = "{0}+{1}=".format(x,y))
mylabel3.configure(text="{0} of {1} correct".format(correct, correct+incorrect))

I cant generate a random number and print it

I can't generate the number because I get the error NameError: name 'z' is not defined.
import tkinter as tk
from random import randint
def randomize():
z.set ( randint(x.get(),y.get()))
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root)
enterY = tk.Entry(root)
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I need help to resolve the error
You have 2 problems here.
One. You are missing z = tk.Intvar() in the global namespace.
Two. You need to assign each entry field one of the IntVar()'s.
Keep in mind that you are not validating the entry fields so if someone types anything other than a whole number you will run into an error.
Take a look at this code.
import tkinter as tk
from random import randint
def randomize():
z.set(randint(x.get(),y.get()))
print(z.get()) # added print statement to verify results.
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar() # added IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root, textvariable=x) # added textvariable
enterY = tk.Entry(root, textvariable=y) # added textvariable
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()

Clickable menu Crashing

I have made a test Code for a school project that was assigned to the class but when i run the code the tkinter buttons load up, however when you press the button on the Maths section(the only one done), the code would crash, any help would be nice.
from tkinter import *
Window_Blank = Tk()
#Advanced Define
def MathA():
answer = input()
answer = int(answer)
print("If A=12*2 and B=15*3, What does AB-B= ")
if answer == 1035:
print("Correct")
else:
print("Incorrect")
print("The Answer was 1035")
def Math():
print(MathA())
return
def Science():
return
def Agriculture():
return
def Geographical():
return
#Basic Define
Frame1 = Frame(Window_Blank)
Frame2 = Frame(Window_Blank)
Frame3 = Frame(Window_Blank)
Frame4 = Frame(Window_Blank)
Button1 = Button(Frame1, text="Math Questions", fg="red", command=Math)
Button2 = Button(Frame2, text="Science Questions", fg="blue", command=Science)
Button3 = Button(Frame3, text="Agricultural Questions", fg="green", command=Agriculture)
Button4 = Button(Frame4, text="Geographical Questions", fg="purple", command=Geographical)
#Framework for the menu
Frame1.grid(row=0, column=0)
Frame2.grid(row=0, column=1)
Frame3.grid(row=0, column=2)
Frame4.grid(row=0, column=3)
Button1.grid(row=1)
Button2.grid(row=2)
Button3.grid(row=3)
Button4.grid(row=4)
Window_Blank.mainloop()
Change this:
def MathA():
print("If A=12*2 and B=15*3, What does AB-B= ")
answer = input()
answer = int(answer)
if answer == 1035:
print("Correct")
else:
print("Incorrect")
print("The Answer was 1035")
And:
def Math():
MathA()
return

entry.get() function won't change value of a variable

I have some code which asks the user to enter a word they'd like to encrypt and then the program will encrypt the word and display it on a label.
I was wondering why the following code works:
import tkinter
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
letters += letters.lower()
encryption_code += encryption_code.lower()
window = tkinter.Tk()
encryption_code_entry = tkinter.Entry(window)
entry = tkinter.Entry(window)
enc = dict(zip(letters,encryption_code))
string = 'hello world'
encr = "".join([enc.get(ch, ch) for ch in string])
def encrypt():
encrypt_label.pack()
entry.pack()
encrypt_confirm.pack()
encrypt_button.destroy()
def display_encrypt():
display_enc = encr
encrypted_label.pack()
new_message.config(text=str(display_enc))
new_message.pack()
encrypt_confirm = tkinter.Button(window, text="Confirm", command=display_encrypt)
new_message = tkinter.Label(window, text="", font=('Helvetica', 10))
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + " has been encrypted into the following: ")
encrypt_button = tkinter.Button(window, text="Encrypt", command=encrypt)
encrypt_button.pack()
encrypt_label = tkinter.Label(window, text="Please enter the message you'd like to encrypt", font=('Helvetica', 14))
window.mainloop()
But if I change string = 'hello world' (which is what I'd like to do) to string = entry.get() nothing is displayedonnew_message`. Also,
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + "has been encrypted into the following: ")
doesn't display what the user typed in the entry box so I'm almost 100% sure I'm misusing the entry.get() function.
You in fact need to have the entry.get() under display_encrypt().
Every time the encrypt_confirm button is pressed, it calls display_encrypt which will then in turn be able to get the current string in entry every time it is pressed by the user.
I edited your code a bit and it seems to be working.
Notice that I have removed string and encr as they were now redundant variables.
import tkinter
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
letters += letters.lower()
encryption_code += encryption_code.lower()
window = tkinter.Tk()
encryption_code_entry = tkinter.Entry(window)
entry = tkinter.Entry(window)
enc = dict(zip(letters,encryption_code))
string = 'hello world'
def encrypt():
encrypt_label.pack()
entry.pack()
encrypt_confirm.pack()
encrypt_button.destroy()
def display_encrypt():
display_enc = "".join([enc.get(ch, ch) for ch in entry.get()])
encrypted_label.pack()
new_message.config(text=str(display_enc))
new_message.pack()
encrypt_confirm = tkinter.Button(window, text="Confirm", command=display_encrypt)
new_message = tkinter.Label(window, text="", font=('Helvetica', 10))
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + " has been encrypted into the following: ")
encrypt_button = tkinter.Button(window, text="Encrypt", command=encrypt)
encrypt_button.pack()
encrypt_label = tkinter.Label(window, text="Please enter the message you'd like to encrypt", font=('Helvetica', 14))
window.mainloop()
You are calling entry.get() well before the user ever has a chance to enter anything. You need to call it and reset the label in response to an event, such as the user pressing <Return>, clicking a button, etc.

Categories