Simple Guessing Game not working - python-3.x

This is supposed to be a guessing game. If the user submits a number that is higher than the pre-set value (which is 10), it will say go lower. And if the user submits a lower number, it will say go higher. The problem I'm facing is that it only tells me to go higher with every integer or even string I type in. Any clue what the problem might be?
Also, the reason I turned 10 into a string is because it gives me an error if it's an integer.
from tkinter import *
# Simple guessing game
window = Tk()
def number():
if typed == key:
print("This is the correct key")
elif typed > key:
print("Go lower!")
else:
print("Go higher!")
e = Entry(window)
e.pack()
key = str(10)
typed = e.get()
b = Button(window, text="Submit", command=number)
b.pack()
window.mainloop()

You need to update the value on each submit and check or else it will stay constant. The reason why it did not work is because you assigned typed to e.get() on program start, which is an empty string. You need to update it on every click, or put typed inside the function.
You also need to make key an integer, and convert the entry value into an integer, or else you're lexicographically comparing strings. Also, you can add a try/except to handle if the user does not enter an integer, as shown below.
I would personally pass the entry's value into the function and on click use a lambda to process the check:
from tkinter import *
# Simple guessing game
window = Tk()
def number(num): # Passing in string instead of using typed
try:
intNum = int(num) # Here we convert num to integer for comparison
if intNum == key:
print("This is the correct key")
elif intNum > key:
print("Go lower!")
else:
print("Go higher!")
except ValueError: # If user doesn't enter a convertable integer, then print "Not an integer!"
print("Not an integer!")
e = Entry(window)
e.pack()
key = 10 # Key is an integer here!
b = Button(window, text="Submit", command=lambda: number(e.get())) # Here's a lambda where we pass in e.get() to check
b.pack()
window.mainloop()
So now it will pass the value in, then compare instead of using typed. lambda: number(num) just allows the passing of an argument in the command argument. Here's a link to docs regarding lambdas. Without lambdas, here's a hastebin demonstrating without function arguments.

Related

How do I get the value from an option in tkinter after it has passed through a function?

I'm using tkinter to create an option menu for a user to interact with, when the selection has been made it will pass through a function to return an integer based on the input. I want to be able to return the integer back to a variable outside of the function so it can be received by another file. My problem is that python will keep returning the button as the command has not yet been processed.
from tkinter import *
Final = [] ##List containing options
master = Tk()
variable = StringVar(master)
variable.set(Final[0]) # default value
w = OptionMenu(master, variable, *Final)
w.pack()
def ok():
global choice
choice = variable.get()
global x
x = 0
for i in Final:
if str(i) == str(choice):
break
x += 1
button = Button(master, text="Choose", command=ok)
button.pack()
values = x

Formatting entered text in Python Tkinter Entry widget after user interacts with another widget

If a user enters 25000 into a tkinter entry widget, is there a way to make the widget automatically display the text that was just entered as $25,000.00 once the user interacts with anything else? I've used '${:.,2f}'.format() in other projects, but I'm not sure how to use it with tkinter. Perhaps there is another method entirely when building code in tkinter. Thanks in advance for any advice you might have to offer!
from tkinter import *
from tkinter import messagebox
window=Tk()
window.title("APY Accrued Value Calculator")
def Button1Function():
exit()
def Button2Function(Entry1,Entry2,Entry3):
while True:
if Entry1==0 or Entry2==0 or Entry3==0:
messagebox.showerror("Error Detected","All fields must have a
number value greater than zero")
return None
if Entry3==int(Entry3):
Entry3=int(Entry3)
else:
messagebox.showerror("Error Detected","Number of years must be
a whole number.")
return None
try:
if Entry2==int(Entry2):
Entry2=int(Entry2)
except: pass
AccruingAmount=Entry1
for i in range(0,Entry3):
AccruingAmount=AccruingAmount*(1+(Entry2/100))
Entry1='${:,.2f}'.format(Entry1)
Entry2='{}%'.format(Entry2)
AccruingAmount='${:,.2f}'.format(AccruingAmount)
message="
"
CalculationMessage=Message(window,width=345,text=message)
message="If "+Entry1+" is deposited and left for "+str(Entry3)+"
years at an annual interest rate of "+Entry2+", your final return will be:
"+AccruingAmount+"."
CalculationMessage=Message(window,width=345,text=message)
CalculationMessage.grid(row=12,column=0,sticky=(N),pady=(5,0))
break
Label1=Label(window,text="Starting amount:")
Label1.grid(column=0,sticky=(W),padx=(5,0))
StrVar1=StringVar()
Entry1=Entry(window,textvariable=StrVar1)
Entry1.grid(column=0,sticky=(W),padx=(5,0))
Label2=Label(window,text="APY percentage rate:")
Label2.grid(row=3,column=0,sticky=(W),padx=(5,0),pady=(10,0))
StrVar2=StringVar()
Entry2=Entry(window, textvariable=StrVar2)
Entry2.grid(column=0,sticky=(W),padx=(5,0))
Label3=Label(window,text="Number of years that starting amount will be
accruing interest:")
Label3.grid(row=6,column=0,columnspan=2,sticky=(W),padx=(5,0),pady=(10,0))
StrVar3=StringVar()
Entry3=Entry(window, textvariable=StrVar3)
Entry3.grid(row=7,column=0,sticky=(W),padx=(5,0))
BlankRow3=Label(window,text="Calculation results:",font=("bold"))
BlankRow3.grid(row=8,column=0,pady=(10,0))
CalculationBox=Canvas(window,borderwidth=2,width=350,height=25)
CalculationBox.grid(row=12,column=0)
Button1=Button(window,text="Close",width=12,command=Button1Function)
Button1.grid(row=13,column=0,sticky=(W),padx=(5,0),pady=(0,5))
try:
Button2=Button(window,text="Calculate",width=12,command=lambda: Button2Function(float(Entry1.get()),float(Entry2.get()),float(Entry3.get())))
Button2.grid(row=13,column=0,sticky=(E),padx=(0,5),pady=(0,5))
except: messagebox.showerror("Error Detected","Numbers must be entered
into all fields.")
window.mainloop()
Try this code:
import tkinter as tk
root = tk.Tk()
amount = tk.Label(root,text = "$0.00")
amount.grid(row=1,column=0)
def updat():
try:amount.config(text="${:,.2f}".format(float(entry.get())))
except:amount.config(text = "$0.00")
entry = tk.Entry(root)
entry.grid(row=0,column=0)
entry.bind("<Key>",lambda v: root.after(10,updat))
root.mainloop()
Running:

program crashes when press button - Number guess game - Tkinter

I have no idea why this is not working, I have been looking and I cant see whats wrong I have messed with it for a while all I want is for it to work.
gets input outputs numbers equal to randomly generated if full number equals the random then you win but it just crashes when I press the button
from tkinter import *
from tkinter import ttk
import random
master = Tk()
master.title('Guess The Number!')
global answer
global guess_entry
global guess_display
answer = str(random.randint(1000,9999))
guess_counter = 0
def callback():
print('Button pressed')
counter = 0
correct = []
while counter < 4:
if guess_entry.get() == answer:
correct.append('Well done, that is correct')
break
elif guess_entry.get()[counter] == answer[counter]:
correct.append(guess_entry.get[counter])
counter += 1
guess_display['text'] = ' '.join(str(correct))
def Help():
win = Toplevel()
win.title('Help')
l = Label(win, text="Guess a 4 digit number and I will tell you\n what you got right,\n keep trying until you get it in the \ncorrect order with correct numbers")
l.grid(row=0, column=0)
b = Button(win, text="Okay", command=win.destroy)
b.grid(row=1, column=0)
guess_entry = Entry(master)
guess_check = Button(master, text='Guess', command=callback)
guess_display = Label(master,text='_ _ _ _')
help_button = ttk.Button(master, text="?", command=Help,width=3)
guess_entry.grid(row=0,column=2)
guess_check.grid(row=1,column=2)
guess_display.grid(row=2,column=1)
help_button.grid(row=0,column=4)
master.mainloop()
If the numbers aren't equal the first time through the loop, they won't be equal any other time through the loop since the user won't have a chance to change their answer while the loop is running.
You can see this by adding a print statement:
while counter < 4:
print("counter:", counter, "guess:", guess_entry.get())
...

Not able to select correct function from dropdown box in python tkinter

I am using Python 3.6 and am not able to figure out the logic to select the correct def function when I select a choice from the dropdown box. Below is the code. Please help.
from tkinter import *
root = Tk()
#Combo box
frame = Frame(root)
frame.pack(pady = 30, padx = 10)
tkvar = StringVar(root)
choices = {'gl_Auto','gl_Elec','gl_OP'}
tkvar.set('gl_Auto')
popupMenu = OptionMenu(frame, tkvar, *choices)
popupMenu.pack(side=LEFT,padx=20,pady=20)
Label(frame, text="Select_GL")
def Select_GL(*args): # When I select different gl, it should go to that function
print(tkvar.get())
# link function to change dropdown
tkvar.trace('w', Select_GL)
def keyword_auto():
print(Automotive)
def keyword_elec():
print(Electronics)
def keyword_OP():
print(OP)
root=mainloop()
If you want to go to a function based on the variable value, you simply need to compare the value to an expected string, and call the appropriate function.
def Select_GL(*args):
value = tkvar.get()
if value == "gl_Auto":
keyword_auto()
elif value == 'gl_Elec':
keyword_elec()
else
keyword_OP()

'SyntaxError: invalid syntax' in python 3 IDLE

Why is this a syntax error? And how do I fix it?
class Queue:
#Queue is basicliy a List:
def __init__(self):
self.queue = []
#add to the top of the list (the left side)
def Enqueue(self, num):
if isinstance(num, int):
self.queue.append(num)
#remove from the top of the list and return it to user
def Dequeue(self):
return self.queue.pop(0)
#this function gets inputs from user, and adds them to queue,
#until it gets 0.
def addToQueue(queue, num):
num = input()
while num != 0:
queue.Enqueue(num)
num = input()
The interactive mode (with the >>> prompt) only accepts one statement at a time. You've entered two to be processed at once.
After you've entered the class definition, be sure to add an extra blank line so that the interactive prompt knows you're done. Once you're prompted with a >>>, you'll know it is ready for the function definition.
The rest of your code looks fine. Happy computing :-)

Resources