Python tkinter quiz - python

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()

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()

how to update getting results from an entry box automatically?

I want to update getting results from an entry box in a way that when an integer enters, the equivalent rows of entry boxes appear below that. I have written the below code to make it work using a button. However, I want to make it happen automatically without a button as I entered the number, the rows update. I checked one way of doing that is using the after(). I placed after after() in the function and out of the function but it is not working.
from tkinter import *
root = Tk()
root.geometry("400x400")
n_para = IntVar()
label1 = Label(root, text="Numeric parameters")
label1.grid(row=0, column=0)
entry1 = Entry(root, textvariable=n_para)
entry1.grid(row=0, column=1)
def update():
for i in range(1, n_para.get()+1):
entryX = Entry(root)
entryX.grid(row=i+1, column=0)
entryY = Entry(root)
entryY.grid(row=i+1, column=1)
entryZ = Entry(root)
entryZ.grid(row=i+1, column=2)
root.after(100, update)
root.after(1, update)
button1 = Button(root, text="update", command=update)
button1.grid(row=1, column=0)
root.mainloop()
You should try using the <KeyRelease> event bind.
import tkinter as tk
def on_focus_out(event):
label.configure(text=inputtxt.get())
root = tk.Tk()
label = tk.Label(root)
label.pack()
inputtxt = tk.Entry()
inputtxt.pack()
root.bind("<KeyRelease>", on_focus_out)
root.mainloop()
This types the text entered in real-time.
Edited Code with OP's requirement:
from tkinter import *
root = Tk()
root.geometry("400x400")
n_para = IntVar()
label1 = Label(root, text="Numeric parameters")
label1.grid(row=0, column=0)
entry1 = Entry(root, textvariable=n_para)
entry1.grid(row=0, column=1)
def upd(event):
x = entry1.get()
if not x.isnumeric():
x = 0
for i in range(1, int(x)+1):
entryX = Entry(root)
entryX.grid(row=i+1, column=0)
entryY = Entry(root)
entryY.grid(row=i+1, column=1)
entryZ = Entry(root)
entryZ.grid(row=i+1, column=2)
# root.after(100, update)
root.bind("<KeyRelease>", upd)
# button1 = Button(root, text="update", command=update)
# button1.grid(row=1, column=0)
root.mainloop()

Add labels to the top of a tkinter grid?

The point of this is to press a button and have new rows appear but currently, titles appear above each new row that is added. Instead, I would like to have one row at the top of the grid with column titles. Is there a way to modify this code I already have? Later, I will be incorporating this into a larger tkinter GUI.
from tkinter import *
#------------------------------------
def addbox():
frame =Frame(root)
frame.pack()
#Item
Label(frame, text="Item").grid(row=0, column=0)
ent1 = Entry(frame, width=10)
ent1.grid(row=2, column=0)
#Day
Label(frame, text="Day").grid(row=0, column=1)
ent2 = Entry(frame, width=10)
ent2.grid(row=2, column=1)
#Code
ent3 = Entry(frame, width=10)
ent3.grid(row=2, column=2)
#Factor
ent4 = Entry(frame, width=10)
ent4.grid(row=2, column=3)
all_entries.append( (ent1, ent2, ent3, ent4) )
#Buttons.
showButton = Button(frame, text='Print', command=refresh)
addboxButton = Button(frame, text='Add Item', fg="Red", command=addbox)
#------------------------------------
def refresh():
for number, (ent1, ent2, ent3, ent4) in enumerate(all_entries):
print (number, ent1.get(), ent2.get(), ent3.get(),ent4.get())
#------------------------------------
all_entries = []
root = Tk()
addboxButton = Button(root, text='Add Instrument', fg="Red", command=addbox)
addboxButton.pack()
root.mainloop()
You can check the row count before you add the label:
if len(all_entries) < 1:
Label(frame, text="Item").grid(row=0, column=0)

How to return value to Entry Widget

I don't know how to return or print result to entry widget. I've tried to add code on the res function, but it still doesn't return the result that I want.
import tkinter as tk
from tkinter import *
win = tk.Tk()
win.title("Test")
win.configure(background='black')
enternumber = Label(win, text="Enter Number")
enternumber.grid(column=0, row=0)
var1 = IntVar()
txtenternumber = Entry(win, width=20, textvariable=var1)
txtenternumber.grid(column=1, row=0)
enternumber = Label(win, text="Enter Number")
enternumber.grid(column=0, row=1)
var2 = IntVar()
txtenternumber = Entry(win, width=20, textvariable=var2)
txtenternumber.grid(column=1, row=1)
def res():
result = var1.get()*var2.get()
#here the code i added
resultentry.bind('<Return>', res)
#Here the button should returning result
resultbutton = Button(win, text="Ok", command=res)
resultbutton.grid(column=2, row=2)
resultlabel = Label(win,text="Result")
resultlabel.grid(column=0, row=2)
#I want result printed here
resultentry = Entry(win, width=30)
resultentry.grid(column=1,row=2)
import tkinter as tk
from tkinter import *
win = tk.Tk()
win.title("Test")
win.configure(background='black')
enternumber = Label(win, text="Enter Number")
enternumber.grid(column=0, row=0)
var1 = IntVar()
txtenternumber = Entry(win, width=20, textvariable=var1)
txtenternumber.grid(column=1, row=0)
enternumber = Label(win, text="Enter Number")
enternumber.grid(column=0, row=1)
var2 = IntVar()
txtenternumber = Entry(win, width=20, textvariable=var2)
txtenternumber.grid(column=1, row=1)
def res():
result = var1.get()*var2.get()
resultentry.insert(0,result) # INSERTS RESULT INTO resultentry
resultentry.bind('<Return>', res)
resultbutton = Button(win, text="Ok", command=res)
resultbutton.grid(column=2, row=2)
resultlabel = Label(win,text="Result")
resultlabel.grid(column=0, row=2)
resultentry = Entry(win, width=30)
resultentry.grid(column=1,row=2)
win.mainloop()
Sorry, forgot to add this. Yes, you just need to use resultentry.insert(0, result)and you should be set. I also like using this as a good resource:
https://effbot.org/tkinterbook/entry.htm

Python Tkinter doesn't show the label when I press the button

I have one Input and one button. I want the value of the input (Entry) to when I press the button. When I type print(mtext) it works well, but when I put it in a Label it doesn't work.
Here is the code:
from tkinter import *
root = Tk()
root.title("Mohamed Atef")
root.geometry("900x600")
var = StringVar()
var.set("Please write something")
label = Label(root, textvariable=var, padx=10, pady=10)
#input
text = StringVar()
entry = Entry(root, textvariable=text)
def mohamed():
mtext = text.get()
mohamed = Label(root, textvariable=mtext)
mohamed.pack()
#button
buttonText = StringVar()
buttonText.set("Click me !")
button = Button(root, textvariable=buttonText, command=mohamed)
label.pack()
entry.pack()
button.pack()
root.mainloop()
Same as Flilp, your finished product would look like this
from tkinter import *
root = Tk()
root.title("Mohamed Atef")
root.geometry("900x600")
var = StringVar()
var.set("Please write something")
label = Label(root, textvariable=var, padx=10, pady=10)
#input
text = StringVar()
entry = Entry(root, textvariable=text)
def mohamed() :
mtext = text.get()
mohamed = Label(root, text=mtext)
mohamed.pack()
#button
buttonText = StringVar()
buttonText.set("Click me !")
button = Button(root, textvariable=buttonText, command=mohamed)
label.pack()
entry.pack()
button.pack()
root.mainloop()
If you just want text that's in your Entry to appear under your labels you could do:
def mohamed():
mohamed = Label(root, textvariable=text)
mohamed.pack()
Your code didn't work because value passed as textvariable should be tkinter StringVar() not string.
If you don't want the text to be constantly updated when you change your Entry you should do:
def mohamed():
mtext = text.get()
mohamed = Label(root, text=mtext)
mohamed.pack()

Categories