How to enhance quiz game for multiple choice? - python

I am not sure how I should create this as a "multiple choice" quiz game.
I don't know how to continue on. I am not sure how to use class in this instance. If I can get the first question working with answers, I'm sure I am continue on from there but I am in need of help.
Here is my current code:
from tkinter import *
from tkinter import ttk
#User Interface Code
root = Tk() # Creates the window
root.title("Quiz Game")
def new_window():
newWindow = Toplevel()
message = Label(newWindow, text="What is the capital of France?", font =
("Arial", "24"), pady=30)
display = Label(newWindow, width=150, height=40)
class letsQuiz:
def __init__(self, questions, answers):
self.questions = questions
self.answers = answers
self.label = Label(newWindow, text="What is the capital of France?")
self.label.pack()
self.answer1button = Button(newWindow, text="Madrid")
self.answer2button = Button(newWindow, text="Paris")
self.answer3button = button(newWindow, text="London")
self.answer1button.pack()
self.answer2button.pack()
self.answer3button.pack()
message.pack()
display.pack()
message_label1 = Label(text="Let's quiz some of your knowledge :)", font = (
"Arial", "25"), padx=40, pady=20)
message_label2 = Label(root, text="Click 'Continue' to begin.",
wraplength=250)
button1 = Button(root, text ="Continue", command=new_window, width=16,
bg="red")
display2 = Label(root, width=100, height=30)
message_label1.pack()
message_label2.pack()
button1.pack()
display2.pack()
root.mainloop() # Runs the main window loop

There you go, This should set you up with a good base to work on. I've added few comments to help you out. I've kept most your code intact so you can understand easily. Note that this is no where an optimal way to code a good quiz game. But okay if you're starting on it.
Scoring can be done using lot of if statements and instance variables to keep track of. Good luck !
from tkinter import *
from tkinter import ttk
#User Interface Code
root = Tk() # Creates the window
root.title("Quiz Game")
def new_window():
newWindow = Toplevel()
message = Label(newWindow, font =
("Arial", "24"), pady=30)
display = Label(newWindow, width=150, height=40)
return newWindow
class letsQuiz:
def __init__(self, window):
self.newWindow = window
self.question_counter = 0
# Add your questions and answers here
self.questions = ['# QUESTION: 1', '# QUESTION: 2', '# QUESTION: 3', '# QUESTION: 4']
# Each list is a set of answers corresponding to question
self.answers = [['question_1_Answer_1', 'question_1_Answer_2', 'question_1_Answer_3'],
['question_2_Answer_1', 'question_2_Answer_2', 'question_2_Answer_3'],
['question_3_Answer_1', 'question_3_Answer_2', 'question_3_Answer_3'],
['question_4_Answer_1', 'question_4_Answer_2', 'question_4_Answer_3']]
self.label = Label(self.newWindow, text=self.questions[self.question_counter], font =
("Arial", "24"), pady=30)
self.answer1button = Button(self.newWindow, text=self.answers[self.question_counter][0])
self.answer2button = Button(self.newWindow, text=self.answers[self.question_counter][1])
self.answer3button = Button(self.newWindow, text=self.answers[self.question_counter][2])
self.nextButton = Button(self.newWindow, text="Next", command=self.next_question)
def pack_all(self):
'''
Packs all widgets into the window
'''
self.label.pack()
self.answer1button.pack()
self.answer2button.pack()
self.answer3button.pack()
self.nextButton.pack()
def forget_all(self):
'''
Removes all widgets from the window
'''
self.label.pack_forget()
self.answer1button.pack_forget()
self.answer2button.pack_forget()
self.answer3button.pack_forget()
self.nextButton.pack_forget()
def next_question(self):
'''
Updates the question and its corresponding answers
'''
self.question_counter += 1
self.forget_all() # remove old question
try:
self.label = Label(self.newWindow, text=self.questions[self.question_counter], font =
("Arial", "24"), pady=30)
self.answer1button = Button(self.newWindow, text=self.answers[self.question_counter][0])
self.answer2button = Button(self.newWindow, text=self.answers[self.question_counter][1])
self.answer3button = Button(self.newWindow, text=self.answers[self.question_counter][2])
self.nextButton = Button(self.newWindow, text="Next", command=self.next_question)
except IndexError:
self.forget_all()
msg = Label(self.newWindow, text="You have completed the quiz Thank you for playing, Close to EXIT", font =
("Arial", "24"), pady=30)
msg.pack()
self.pack_all() # place in the new question
quiz = letsQuiz(new_window() )
#message.pack()
#display.pack()
message_label1 = Label(text="Let's quiz some of your knowledge :)", font = (
"Arial", "25"), padx=40, pady=20)
message_label2 = Label(root, text="Click 'Continue' to begin.",
wraplength=250)
button1 = Button(root, text ="Continue", command=quiz.pack_all, width=16,
bg="red")
display2 = Label(root, width=100, height=30)
message_label1.pack()
message_label2.pack()
button1.pack()
display2.pack()
root.mainloop() # Runs the main window loop

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 do you make it so that after the user presses a button, they can input their information in Tkinter for python 3.7

I was wondering if someone could help me as I am fairly new to Tkinter and got some good help on here before.
My query is that I am trying to make a budget calculator sort of program and am using Tkinter. I am wondering how do you get user inputs where the user can click on a button called "Incomes" or "Expenses" and then they can input all their numbers and it will be printed below in the form of a table.
My code is below any information will really help me and also any other points you can point out about my code so far will be greatly appreciated!
from time import sleep
from tkinter import *
from tkinter import messagebox, ttk, Tk
root = Tk()
class GUI():
def taskbar(self):
menu = Menu(root)
file = Menu(menu)
root.config(menu=file)
file.add_command(label="Exit", command=self.exit_GUI)
file.add_command(label="Information", command=self.info_popup)
menu.add_cascade(label="File", menu=file)
def Main_Menu(self):
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
Income_button = Button(topFrame, text="Enter your incomes", command=self.Income)
Expense_button = Button(topFrame, text="Enter your expenses", command=self.Expense)
Total_button = Button(bottomFrame, text="View Results", command=self.Total)
Income_button.pack()
Expense_button.pack()
Total_button.pack()
def Income(self):
Income_heading = Label(Toplevel(root), text="Please enter the incomes below!", font=("arial", 50, "bold"), fg="blue").pack()
def Expense(self):
Expense_heading = Label(Toplevel(root), text="Please enter the expenses below!", font=("arial", 50, "bold"), fg="blue").pack()
def Total(self):
pass
def exit_GUI(self):
exit()
def info_popup(self):
pass
g = GUI()
g.taskbar()
g.Main_Menu()
#g.Income()
#g.Expense()
g.Total()
g.info_popup()
root.mainloop()
You should use class attributes to hold the values. Then we can use a combination of lambda, entry, and a function to set those values.
This below example will show you how one can set values from a top level window inside the class.
import tkinter as tk
class GUI():
def __init__(self):
menu = tk.Menu(root)
file = tk.Menu(menu)
root.config(menu=file)
file.add_command(label="Exit", command=self.exit_GUI)
file.add_command(label="Information", command=self.info_popup)
menu.add_cascade(label="File", menu=file)
self.income_var = 0
self.expense_var = 0
self.total_var = 0
top_frame = tk.Frame(root)
top_frame.pack()
bottom_frame = tk.Frame(root)
bottom_frame.pack(side="bottom")
tk.Button(top_frame, text="Enter your incomes", command=self.income).pack()
tk.Button(top_frame, text="Enter your expenses", command=self.expense).pack()
tk.Button(bottom_frame, text="View Results", command=self.total).pack()
def set_vars(self, entry, var):
if var == "income":
self.income_var = entry.get()
print(self.income_var)
if var == "expense":
self.expense_var = entry.get()
print(self.expense_var)
if var == "total":
self.total_var = entry.get()
print(self.total_var)
def income(self):
top = tk.Toplevel(root)
tk.Label(top, text="Please enter the incomes below!", font=("arial", 12, "bold"), fg="blue").pack()
entry = tk.Entry(top)
entry.pack()
tk.Button(top, text="Submit", command=lambda: (self.set_vars(entry, "income"), top.destroy())).pack()
def expense(self):
top = tk.Toplevel(root)
tk.Label(top, text="Please enter the expenses below!", font=("arial", 12, "bold"), fg="blue").pack()
entry = tk.Entry(top)
entry.pack()
tk.Button(top, text="Submit", command=lambda: (self.set_vars(entry, "expense"), top.destroy())).pack()
def total(self):
pass
def exit_GUI(self):
self.destroy()
def info_popup(self):
pass
root = tk.Tk()
g = GUI()
root.mainloop()
The widget to enter information in Tkinter is the widget Entry. For get the text you could use get(). Example:
def income_func(self, event):
text = Income_entry.get() #For get the text into the entry
def Income(self):
top_lvl = Toplevel(root)
Income_heading = Label(top_lvl , text="Please enter the incomes below!", font=("arial", 50, "bold"), fg="blue").pack()
Income_entry = Entry(top_lvl)
Income_entry.pack()
Income_entry.bind("<Key-Return>", income_func) #When user press `enter` this call to income_func with argument `event`

New window label

how do I position my label which says "Question One" in my def new_window() function. As you run it the label is being positioned at the bottom, And i want it to be applied on the top.
from tkinter import *
from tkinter import ttk
#User Interface Code
root = Tk() # Creates the window
root.title("Quiz Game")
def new_window():
newWindow = Toplevel(root)
display = Label(newWindow, width=150, height=40)
message = Label(newWindow, text="Question One", font = ("Arial", "24"))
display.pack()
message.pack()
display2 = Label(root, width=100, height=30, bg='green')
button1 = Button(root, text ="Continue", command=new_window, width=16,
bg="red")
message_label1 = Label(text="A Quiz Game", font = ("Arial", "24"), padx=40,
pady=20)
message_label2 = Label(root, text="Click 'Continue' to begin.",
wraplength=250)
display2.pack()
button1.pack()
message_label1.pack()
message_label2.pack()
root.mainloop() # Runs the main window loop
You are packing in the wrong order. Do not pack display before your message. So just swapping the order will fix the issue.
Here is the code. Replace your def new_window(): with this
def new_window():
newWindow = Toplevel()
message = Label(newWindow, text="Question One", font = ("Arial", "24"))
display = Label(newWindow, width=150, height=40)
message.pack()
display.pack()
pack method just blindly packs the widget into the window. And the next pack will be done below it if there is space. So take care of the order while packing widgets :)

How do I make a table that updates from user input in the box before with tkinter?

The overall aim of the program is to make a scoreboard that displays the scores of both teams and individuals. It needs to contain 4 columns and 5 rows for the team aspect and 20 separate spaces for individual inputs.
I want to make a table that uses user input using the previous box that I had created. So far, I have created up to the point where the user needs to input their team name and displays a table with no entries. I need it to display the events that they are doing as well as the score and their team name/name.
I am new to Python and tkinter so anyone who can help me solve this problem would be great!
from tkinter import *
import tkinter as tk
from time import sleep
def team_name():
print('Okay, what is your team name?')
window = Toplevel(main)
thirdLabel = Label(window, text='Please enter your team name below:',
bg='black', fg='yellow')
thirdLabel.pack()
Label2 = Label(window,text = '')
Label2.pack(padx=15,pady= 5)
entry2 = Entry(window,bd =5)
entry2.pack(padx=15, pady=5)
buttonconfirm1 = Button(window, text='Confirm',command=confirm1)
buttonconfirm1.pack()
def confirm1 ():
window = Toplevel(main)
confirmLabel = Label(window, text='Scoreboard', bg='black',
fg='yellow')
confirmLabel.pack(fill=X)
def table ():
window = Toplevel(main)
label3 = Label(window, text='Team name/Individual name', bg='black',
fg='yellow')
label3.pack()
firstBox = Entry(window, bd=1)
firstBox.pack()
secondBox = Entry(window, bd=1)
secondBox.pack()
thirdBox = Entry(window, bd=1)
thirdBox.pack()
def scoreboard():
window = Toplevel(main)
entry_1 = Label(window, text = '')
entry_2 = Label(window, text = '')
def individual_name():
print('Okay, what is you name?')
window = Toplevel(main)
secondLabel = Label(window, text='Please enter your name below',
bg='black', fg='yellow')
secondLabel.pack()
Label1 = Label(window,text = '')
Label1.pack(padx=15,pady= 5)
entry1 = Entry(window,bd =5)
entry1.pack(padx=15, pady=5)
buttonConfirm = Button(window, text='Confirm', command=table)
buttonConfirm.pack()
def confirm ():
window = Toplevel(main)
confirmLabel = Label(window, text='Scoreboard', bg='black', fg='yellow')
confirmLabel.pack(fill=X)
def close():
main.destroy()
main = Tk()
main.maxsize(800,600)
# Labels section
main_menu_label = Label(main, text='Welcome to the scoreboard! Please
select from the options below:', bg='Black',
fg='white')
# Using a photo for top frame on menu and making a label to place it
photo = PhotoImage(file='Scoreboard.gif')
photo_label = Label(main, image=photo)
photo_label.pack(side=TOP)
# Invisible frames for widget placement
top_frame = Frame(main)
top_frame.pack()
bottom_frame = Frame(main)
bottom_frame.pack(side=BOTTOM)
print('Okay! What is your team name?')
# Buttons for main menu and display on the screen
first_button = Button(top_frame, text='Are you entering as an
individual?', fg='yellow', bg='black',
command=individual_name)
second_button = Button(bottom_frame, text='Are you entering as a team?',
fg='yellow', bg='black', command=team_name)
quit_button = Button(bottom_frame, text='Quit?', fg='yellow', bg='black',
command=close)
first_button.pack()
second_button.pack()
quit_button.pack()
main.mainloop()
Sorry if this is a bit confusing, I can't really explain much more than I already have!

tkinter (unsure of my error possibly due to .destroy())

from Tkinter import *
import random
menu = Tk()
subpage = Tk()
entry_values = []
population_values = []
startUpPage = Tk()
def main_menu(window):
window.destroy()
global menu
menu = Tk()
frame1 = Frame(menu)
menu.resizable(width=FALSE, height=FALSE)
button0 = Button(menu, text="Set Generation Zero Values", command=sub_menu(menu))
button1 = Button(menu, text="Display Generation Zero Values")
button2 = Button(menu, text="Run Model")
button3 = Button(menu, text="Export Data")
button4 = Button(menu, text="Exit Program", command=menu.destroy)
button0.grid(row=0, column=0, sticky=W)
button1.grid(row=2, column=0, sticky=W)
button2.grid(row=3, column=0, sticky=W)
button3.grid(row=4, column=0, sticky=W)
button4.grid(row=5, column=0, sticky=W)
menu.mainloop()
def sub_menu(window):
global subpage
window.destroy()
subpage = Tk()
subpage.resizable(width=FALSE, height=FALSE)
#defining sub page items
button5 = Button(subpage, text="Save Generation Data",command = main_menu(subpage))
juveniles_label0 = Label(subpage,text="Juveniles")
adults_label1 = Label(subpage,text="Adults")
seniles_label2 = Label(subpage,text="Seniles")
population_label3 = Label(subpage,text="Popultation")
survival_rate_label4 = Label(subpage,text="Survival Rate (Between 0 and 1)")
entry0 = Entry(subpage)
entry1 = Entry(subpage)
entry2 = Entry(subpage)
entry3 = Entry(subpage)
entry4 = Entry(subpage)
entry5 = Entry(subpage)
button4.grid(row=1, column= 6, sticky=E)
juveniles_label0.grid(row=0, column=1)
adults_label1.grid(row=0, column=2)
seniles_label2.grid(row=0, column=3)
population_label3.grid(row=1, column=0)
survival_rate_label4.grid(row=2, column=0)
entry0.grid(row=1, column=1)
entry1.grid(row=1, column=2)
entry2.grid(row=1, column=3)
entry3.grid(row=2, column=1)
entry4.grid(row=2, column=2)
entry5.grid(row=2, column=3)
#add entry 6 7 8
subpage.mainloop()
main_menu(subpage)
main_menu(startUpPage)
I'm very new to coding and stackoverflow. I am trying to create a GUI that has a main page which will be opened first and a sub page which will be opened by clicking a button which will be stored in the main page. my issue is that I have no clue why it isn't opening my main page. my thought is that it is something to do with the .destroy() or something similar. any help would be much appreciated.
As a general rule, you should create exactly one instance of Tk for the life of your program. That is how Tkinter is designed to be used. You can break this rule when you understand the reasoning behind it, though there are very few good reasons to break the rule.
The simplest solution is to implement your main menu and your sub menu as frames, which you've already done. To switch between them you can simply destroy one and (re)create the other, or create them all ahead of time and then remove one and show the other.
For example, the following example shows how you would create them ahead of time and simply swap them out. The key is that each function needs to return the frame, which is saved in a dictionary. The dictionary is used to map symbolic names (eg: "main", "sub", etc) to the actual frames.
def main_menu(root):
menu = Frame(root)
button0 = Button(menu, text="Set Generation Zero Values",
command=lambda: switch_page("sub"))
...
return menu
def sub_menu(root):
subpage = Frame(root)
button5 = Button(subpage, text="Save Generation Data",
command = lambda: switch_page("main"))
...
return subpage
def switch_page(page_name):
slaves = root.pack_slaves()
if slaves:
# this assumes there is only one slave in the master
slaves[0].pack_forget()
pages[page_name].pack(fill="both", expand=True)
root = Tk()
pages = {
"main": main_menu(root),
"sub": sub_menu(root),
...
}
switch_page("main")
root.mainloop()
For a more complex object-oriented approach see Switch between two frames in tkinter
heres some code that does what you want.. make a window, destroy it when button is clicked and then make a new window...
from Tkinter import *
import random
def main_menu():
global root
root = Tk()
b = Button(root,text='our text button',command = next_page)
b.pack()
def next_page():
global root,parent
parent = Tk()
root.destroy()
new_b = Button(parent,text = 'new Button',command=print_something)
new_b.pack()
def print_something():
print('clicked')
main_menu()
root.mainloop()
parent.mainloop()
ps. ive done this in python3 so keep that in mind though it wouldnt be a problem in my opinion

Categories