How to wait for input in Entry widget in tkinter - python

I am trying to make a quiz in tkinter, and I have five questions. But, I want to wait for an answer to be inputted to the entry widget. I know I will probably need a button, but I don't know how I would go about doing that.
My code so far:
for i in range(5):
randChoose = random.choice(choose)
questionLabel = Label(top, text=full[randChoose]).grid(row=0, column=0)
answerLabel = Label(top, text="Answer:").grid(row=1, column=0)
answerEntry = Entry(top, borderwidth=5).grid(row=1,column=1)
if answerEntry.get() == aFull[randChoose]:
correctLabel = Label(top, text="Correct!",fg="green").grid(row=2,column=0)
score += 1
scoreLabel = Label(top, text=f"Your Score is {score}",fg="green").grid(row=2,column=1)
else:
wrongLabel = Label(top, text="Incorrect!",fg="red").grid(row=2,column=0)
scoreLabel = Label(top, text=f"Your Score is {score}",fg="red").grid(row=2,column=1)
choose.remove(randChoose)

First, add a button
button_pressed = StringVar()
this variable button_pressed will tell us if the button was pressed or not
(we set button_pressed to a StringVar() so .set() can change this variable, in the button's command)
button = Button(app, text="Enter", command=lambda: button_pressed.set("button pressed"))
when the button is pressed it will set the variable button_pressed, to "button pressed"
button.grid(row=1, column=1)
Then, wait until the button is pressed
button.wait_variable(button_pressed)
this code will wait until the varialbe button_pressed is changed (to anything)
Finally, check the entry
if answerEntry.get() == aFull[randChoose]: etc.
Final code should look something like this:
for i in range(5):
randChoose = random.choice(choose)
questionLabel = Label(app, text=full[randChoose]).grid(row=0, column=0)
answerLabel = Label(app, text="Answer:").grid(row=1, column=0)
answerEntry = Entry(app, borderwidth=5).grid(row=1,column=1)
button_pressed = StringVar()
button = Button(app, text="Enter", command=lambda: button_pressed.set("button pressed"))
button.grid(row=1, column=1)
button.wait_variable(button_pressed)
if answerEntry.get() == aFull[randChoose]:
correctLabel = Label(app, text="Correct!", fg="green").grid(row=2, column=0)
score += 1
scoreLabel = Label(app, text="Your Score is {score}", fg="green").grid(row=2, column=1)
else:
wrongLabel = Label(app, text="Incorrect!", fg="red").grid(row=2, column=0)
scoreLabel = Label(app, text="Your Score is {score}", fg="red").grid(row=2, column=1)
choose.remove(randChoose)
and you probobly want to destroy this button so on the next question it wont display 2 buttons
button.destroy()

Related

Python tkinter how to save a variable in a list and return it

I am trying to make a program that records user input (drinks) and displays these inputs when a person wants to view them. .
Specifically, I want the drinks to be displayed when the user clicks the 'View Log' button (second_button). I think this needs to be done in the viewlog function, but I am stuck with the best way to do this. I am unsure of how to best store the inputs and how to retrieve them.
from tkinter import *
root = Tk()
root.title('Simple App')
first_label = Label(root, text="Welcome to the program", font=('Arial', 20)).pack()
def save_drink(added_drink, top):
global drinks_list
drinks_list = []
newtop = Toplevel(root)
newtop.geometry("200x200")
newtop.title("Drink Added")
label = Label(
newtop,
text= "{} Added".format((added_drink.get())), font=('Mistral 20')).pack()
close_btn = Button(newtop, text='Close', font=('Mistral 20'), command=lambda t=top, n=newtop: close(t,n))
close_btn.pack()
drinks_list.append(added_drink.get())
def add_drink():
top = Toplevel(root)
top.geometry("750x250")
top.title("Record Drink")
label = Label(top, text= "What drink did you have?", font=('Mistral 18')).pack()
added_drink = Entry(top, font=6)
added_drink_string = str(added_drink)
added_drink.pack()
added_drink_button = Button(top, text='Add Drink', font=3,
command=lambda: save_drink(added_drink, top)).pack()
def close(top, newtop):
top.destroy()
newtop.destroy()
def viewlog():
logtop = Toplevel(root)
logtop.title('Drinks Log')
label_text = Label(logtop, text="Today's Drinks", font=('Arial', 20)).pack()
label2 = Label(logtop, text=print(drinks_list), font=('Arial', 16))
# here we need to take the items in drinks_list and display them on a screen
close_btn = Button(logtop, text="Close", pady=20, font=('Times New Roman', 20), command=logtop.destroy).pack()
first_button = Button(root, text="Add drink", command=add_drink).pack()
second_button = Button(root, text="View log", command=viewlog).pack()
root.mainloop()
you need to pack the label, and remove print() from the label text variable
label2 = Label(logtop, text=(drinks_list), font=('Arial', 16)).pack()

Trying to create a user name and password to log onto next tkinter window. If user and pass correct login button goes to next screen

Here are the labels and buttons I am using, I want the login button to check for passwords in code, then if correct go to the next screen.
from tkinter import *
root = Tk()
# Main window of Application
root.title("Please Login")
root.geometry("300x150")
root.config(background='lightblue', borderwidth=5)
# Creating Label Widget
myLabel1 = Label(root, text="Username :", background='lightblue')
myLabel2 = Label(root, text="Password :", background='lightblue')
# Entry fields
username_1 = Entry(root)
password_1 = Entry(root, show='*')
# Putting labels onto screen
myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1, column=0)
# Entry field Locations
username_1.grid(row=0, column=1)
password_1.grid(row=1, column=1)
Here i have the command quit button but having a hard time with the command for login to go to next window.
# Creating Buttons
loginButton1 = Button(root, text="Login")
cancelButton3 = Button(root, text="Cancel", command=quit)
# Putting buttons onto screen
loginButton1.grid(row=6, column=1)
cancelButton3.grid(row=7, column=1)
# New window
root.mainloop()
That is a lot for one question... I'll try to give you an idea of how you can do this though. I usually do not create a whole new window; I simply change the already existing window.
from tkinter import *
root = Tk()
# Main window of Application
root.title("Please Login")
root.geometry("300x150")
root.config(background='lightblue', borderwidth=5)
# Possible Login
possible_users = {'user1': 'user1_pass', 'user2': 'user2_pass'} # dictionary of corresponding user name and passwords
# StringVars
the_user = StringVar() # used to retrieve input from entry
the_pass = StringVar()
# Creating Label Widget
myLabel1 = Label(root, text="Username :", background='lightblue')
myLabel2 = Label(root, text="Password :", background='lightblue')
bad_pass = Label(root, text="Incorrect Username or Password")
# Entry fields
username_1 = Entry(root, textvariable=the_user)
password_1 = Entry(root, show='*', textvariable=the_pass)
# Putting labels onto screen
myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1, column=0)
# Entry field Locations
username_1.grid(row=0, column=1)
password_1.grid(row=1, column=1)
def login(user):
forget_login_window()
next_window(user)
def check_login():
requested_user = the_user.get()
try:
if possible_users[requested_user] == the_pass.get():
login(requested_user)
else:
bad_pass.grid(row=2, column=1)
except KeyError:
bad_pass.grid(row=2, column=1)
loginButton1 = Button(root, text="Login", command=check_login)
cancelButton3 = Button(root, text="Cancel", command=quit)
# Putting buttons onto screen
loginButton1.grid(row=6, column=1)
cancelButton3.grid(row=7, column=1)
# New window
def forget_login_window(): # forget all the grid items.
username_1.grid_forget()
password_1.grid_forget()
myLabel1.grid_forget()
myLabel2.grid_forget()
loginButton1.grid_forget()
cancelButton3.grid_forget()
bad_pass.grid_forget()
def next_window(my_user):
root.title(my_user) # desired changes here
# you will need to create your tkinter objects (buttons, labels etc) in global and pack / grid / place them here.
root.mainloop()

Using a loop to create multiple drop down menus

I am trying to use a loop to create multiple drop down menus based on an entry in a entry text box after submit is pressed. I have never worked with tkinter before so I am not sure if I am doing this correctly. Any help would be appreciated. the code I have below is what I have but it causes the program to enter into some kind of infinite loop
from Tkinter import *
def callback():
numQues = E1.get()
i = 0
while i < numQues:
variable = StringVar(top)
variable.set("Short Answer") # default value
w = OptionMenu(top, variable, "Short Answer", "Multiple Choice", "Fill in the Blank",
"True of False", "Mathcing", "Ordering")
w.grid(row = i+1, column=0)
i = i+1
top = Tk()
top.geometry("600x600")
L1 = Label(top, text="How many questions will the quiz be?")
L1.grid(row=0, column=0)
E1 = Entry(top, bd = 5)
E1.grid(row=0, column=1)
MyButton1 = Button(top, text="Submit", width=10, command=callback)
MyButton1.grid(row=1, column=1)
top.mainloop()

Python tkinter quiz

I am making a quiz in python using the tkinter module and I am stuck on how to create a button that checks to see if the answer is correct or not. But I would put it in a procedure however the question is already in one.
import tkinter as tk
window = tk.Tk()
window.title("6 Questions")
window.geometry("500x150")
score = 0
def inst():
t = tk.Label(window, text="All you need to do is just answer each question with either a '1, 2, 3' or the actual word.")
t.pack()
def start():
root = tk.Tk()
root.title("question 1")
q = tk.Label(root, text="what type of input holds whole numbers")
q.pack()
a = tk.Label(root, text="1.) int")
a.pack()
b = tk.Label(root, text="2.) string")
b.pack()
c = tk.Label(root, text="3.) float")
c.pack()
ans = tk.Entry(root, width=40)
ans.pack()
#here is the button I want to verify the answer
sub = tk.Button(root, text="Submit")
sub.pack()
greet = tk.Label(window, text="Welcome to the 6 Question Quiz.")
greet.pack()
start = tk.Button(window, command=start, text="Start")
start.pack()
instr = tk.Button(window, text="Instructions", command=inst)
instr.pack()
end = tk.Button(window, text="Exit", command=exit)
end.pack()
Create a function that opens when the submit button is clicked and create RadioButtons rather than Labels.
Like this:
def gettingDecision():
if var.get() is 'True':
messagebox.showinfo('Congrats', message='You Are Correct.Score is {}'.format(score))
else:
messagebox.showinfo('Lose', message='You Are Wrong.')
Question1 = ttk.Label(frame1, text='Q.1.Where does a computer add and compare data ?')
Question1.grid(row=1, column=0, sticky=W)
var = StringVar()
Q1A = ttk.Radiobutton(frame1, text='[A] Hard disk', variable=var, value='False1')
Q1A.grid(row=2, column=0, sticky=W)
Q1B = ttk.Radiobutton(frame1, text='[B] Floppy disk', variable=var, value='False2')
Q1B.grid(row=3, column=0, sticky=W)
Q1C = ttk.Radiobutton(frame1, text='[C] CPU chip', variable=var, value='True')
Q1C.grid(row=4, column=0, sticky=W)
Q1D = ttk.Radiobutton(frame1, text='[D] Memory chip', variable=var, value='False3')
Q1D.grid(row=5, column=0, sticky=W)
submit = ttk.Button(frame1, text='Submit', command=gettingDecision)
submit.grid()
Please note that, ideal way to go would be using classes.
You can define a function, inside of a function.
import tkinter as tk
window = tk.Tk()
window.title("6 Questions")
window.geometry("500x150")
score = 0
def inst():
t = tk.Label(window, text="All you need to do is just answer each question with either a '1, 2, 3' or the actual word.")
t.pack()
def start():
def submit():
print (ans.get())
#or do whatever you like with this
root = tk.Tk()
root.title("question 1")
q = tk.Label(root, text="what type of input holds whole numbers")
q.pack()
a = tk.Label(root, text="1.) int")
a.pack()
b = tk.Label(root, text="2.) string")
b.pack()
c = tk.Label(root, text="3.) float")
c.pack()
ans = tk.Entry(root, width=40)
ans.pack()
#here is the button I want to verify the answer
sub = tk.Button(root, text="Submit", command=submit)
sub.pack()
greet = tk.Label(window, text="Welcome to the 6 Question Quiz.")
greet.pack()
startButton = tk.Button(window, command=start, text="Start")
startButton.pack()
instr = tk.Button(window, text="Instructions", command=inst)
instr.pack()
end = tk.Button(window, text="Exit", command=window.destroy)
end.pack()
window.mainloop()

Checking value of Tkinter Entry widget

I have a submit button here:
submit_btn = Button(top, text="Submit", width=10, command=callback)
submit_btn.grid(row=3, column=1)
and as soon as you click it, it should check the entry field above if the input == "Vincent".
This is the entry field:
top = Tk()
user_label = Label(top, text="User Name")
user_label.grid(row=0, column=0)
username = Entry(top, bd = 5)
username.grid(row=0, column=1)
Is there a way to check if the value of the 'username' Entry object is "Vincent"?
I believe this should do the trick.
submit_btn = Button(top, text="Submit", width=10, command=check_vincent)
def check_vincent():
if username.get() == "Vincent":
print "Hi, Vincent!"
else:
print "Where's Vincent?"

Categories