Set string to text in idle - python

Am new to this so apologies for the basic question
I am trying to set an input box to take letters and numbers
Unfortunately I can only set this field to numbers by using str()
I have tried messing with the code but it will not allow me to use letters
What should I be using instead of str()?
As you can see in my code example, I can only set the username and password to a numerical value rather than alpha numeric values
I believe that I have imported all the correct modules from tk
Have I set the below definitions incorrectly?
- self.Username = StringVar()
- self.Password = StringVar()
Thanks
from tkinter import*
import tkinter.messagebox
from tkinter import ttk
import random
import time
import datetime
def main():
root = Tk()
app = Window1(root)
class Window1:
def __init__(self, master):
self.master =master
self.master.title("Notification Monitoring System")
self.master.geometry('1350x750+0+0')
self.master.config(bg ='white')
self.frame = Frame(self.master, bg ='white')
self.frame.pack()
self.Username = StringVar()
self.Password = StringVar()
self.lblTitle = Label(self.frame, text = 'Welcome to Notification Monitoring', font=('arial',50,'bold'), bg='white',
fg='black')
self.lblTitle.grid(row=0, column=0, columnspan=2, pady=40)
#==============================Frames================================================================
self.LoginFrame1 = LabelFrame(self.frame, width=1350, height=600
,font=('arial',20,'bold'),relief='ridge',bg='pale green', bd=20)
self.LoginFrame1.grid(row=1, column=0)
self.LoginFrame2 = LabelFrame(self.frame, width=1000, height=600
,font=('arial',20,'bold'),relief='ridge',bg='pale green', bd=20)
self.LoginFrame2.grid(row=2, column=0)
#==============================Label And Entry=======================================================
self.lblUsername=Label(self.LoginFrame1, text = 'Username',font=('arial',20,'bold'),bd=22,
bg='pale green', fg='black')
self.lblUsername.grid(row=0,column=0)
self.txtUsername=Entry(self.LoginFrame1,font=('arial',20,'bold'),textvariable= self.Username)
self.txtUsername.grid(row=0,column=1, padx=119)
self.lblPassword=Label(self.LoginFrame1, text = 'Password',font=('arial',20,'bold'),bd=22,
bg='pale green', fg='black')
self.lblPassword.grid(row=1,column=0)
self.txtPassword=Entry(self.LoginFrame1,font=('arial',20,'bold'),show='*', textvariable= self.Password)
self.txtPassword.grid(row=1,column=1, columnspan=2, pady=30)
#==============================Buttons===============================================================
self.btnLogin = Button(self.LoginFrame2, text = 'Login', width = 17,font=('arial',20,'bold'),
command =self.Login_System)
self.btnLogin.grid(row=3,column=0, pady=20, padx=8)
self.btnReset = Button(self.LoginFrame2, text = 'Clear', width = 17,font=('arial',20,'bold'),
command =self.Reset)
self.btnReset.grid(row=3,column=1, pady=20, padx=8)
self.btnExit = Button(self.LoginFrame2, text = 'Exit', width = 17,font=('arial',20,'bold'),
command =self.iExit)
self.btnExit.grid(row=3,column=2, pady=20, padx=8)
#==============================Buttons===========================================================
def Login_System(self):
u =(self.Username.get())
p =(self.Password.get())
if (u ==str(123456789) and p ==str(987654321)):
self.newWindow = Toplevel(self.master)
self.app = Window2(self.newWindow)
else:
tkinter.messagebox.askyesno("Notification Monitoring System", "Invalid login details")
self.Username.set("")
self.Password.set("")
self.txtUsername.focus()
def Reset(self):
self.Username.set("")
self.Password.set("")
self.txtUsername.focus()
def iExit(self):
self.iExit = tkinter.messagebox.askyesno("Notification Monitoring System", "Confirm you want to exit")
if self.iExit > 0:
self.master.destroy()
else:
command = self.new_window
return
def new_window(self):
self.newWindow = Toplevel(self.master)
self.app = Window2(self.newWindow)
class Window2:
def __init__(self, master):
self.master =master
self.master.title("Notification Monitoring System")
self.master.geometry('1350x750+0+0')
self.master.config(bg ='cadet blue')
self.frame = Frame(self.master, bg ='powder blue')
self.frame.pack()
#====================================================================================================
#==============================New window code here==================================================
#===================================================================================================
if __name__== '__main__':
root = Tk()
application = Window1(root)
root.mainloop()

Your question is unclear but I'll try and answer it.
To take input as a number, use:
>>>a = int(input("Enter :"))
Enter :5
>>>print(a*5)
25

Related

How to return entry value from another class?

I am trying to return a value from an Entry widget from another class.
My idea is, when the user has logged in successfully, the welcome screen will show the username that has just logged in.
I have tried using this:
self.userLogged = Label(main, text = self.entry_username.get())
self.userLogged.pack()
i tried linking >self.entry.entry_username.get() from the login class. But here is the error code:
AttributeError: 'App' object has no attribute 'entry_username'
Where I'm I going wrong?
Here is the full code:
from tkinter import *
import tkinter.ttk as ttk
class App():
def __init__(self,master):
notebook = ttk.Notebook(master)
notebook.pack(expand = 1, fill = "both")
#Frames
main = ttk.Frame(notebook)
notebook.add(main, text='Welcome Screen')
self.userLogged = Label(main, text = self.entry_username.get())
self.userLogged.pack()
###################################################################################################################################
##USERS##
###################################################################################################################################
class login(Frame):
def __init__(self, master):
super().__init__(master)
self.label_username = Label(self, text="Username: ",font=("bold",16))
self.label_password = Label(self, text="Password: ",font=("bold",16))
self.entry_username = Entry(self, font = ("bold", 14))
self.entry_password = Entry(self, show="*", font = ("bold", 14))
self.label_username.grid(row=0, sticky=E)
self.label_password.grid(row=1, sticky=E)
self.entry_username.grid(row=0, column=1)
self.entry_password.grid(row=1, column=1)
self.logbtn = Button(self, text="Login", font = ("bold", 10), command=self._login_btn_clicked)
self.logbtn.grid(columnspan=2)
self.pack()
def _login_btn_clicked(self):
# print("Clicked")
username = self.entry_username.get()
password = self.entry_password.get()
# print(username, password)
account_list = [line.split(":", maxsplit=1) for line in open("passwords.txt")]
# list of 2-tuples. Usersnames with colons inside not supported.
accounts = {key: value.rstrip() for key, value in account_list}
# Convert to dict[username] = password, and slices off the line ending.
# Does not support passwords ending in whitespace.
if accounts[username] == password:
self.label_username.grid_forget()
self.label_password.grid_forget()
self.entry_username.grid_forget()
self.entry_password.grid_forget()
self.logbtn.grid_forget()
self.pack_forget()
app = App(root)
else:
print("error")
root = Tk()
root.minsize(950, 450)
root.title("test")
lf = login(root)
root.mainloop()
When working with multiple classes in tkinter it is often a good idea to use class inherancy for the main window and frames. This allows us to use self.master to interact between classes.
That said you have a few things to change. You are using self where it is not needed and you should be doing import tkinter as tk to prevent overwriting of methods.
I have added a class to your code so we use one class for the root window. Then use one class for the login screen and then use one class for the frame after login.
import tkinter as tk
import tkinter.ttk as ttk
class NotebookFrame(tk.Frame):
def __init__(self, username):
super().__init__()
notebook = ttk.Notebook(self)
notebook.pack(expand=1, fill="both")
main = ttk.Frame(notebook)
notebook.add(main, text='Welcome Screen')
tk.Label(main, text=username).pack()
class Login(tk.Frame):
def __init__(self):
super().__init__()
tk.Label(self, text="Username: ", font=("bold", 16)).grid(row=0, sticky='e')
tk.Label(self, text="Password: ", font=("bold", 16)).grid(row=1, sticky='e')
self.entry_username = tk.Entry(self, font=("bold", 14))
self.entry_password = tk.Entry(self, show="*", font=("bold", 14))
self.entry_username.grid(row=0, column=1)
self.entry_password.grid(row=1, column=1)
tk.Button(self, text="Login", font=("bold", 10), command=self.master._login_btn_clicked).grid(columnspan=2)
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("test")
self.minsize(950, 450)
self.login_frame = Login()
self.login_frame.pack()
def _login_btn_clicked(self):
username = self.login_frame.entry_username.get()
password = self.login_frame.entry_password.get()
account_list = [line.split(":", maxsplit=1) for line in open("passwords.txt")]
accounts = {key: value.rstrip() for key, value in account_list}
if accounts[username] == password:
self.login_frame.destroy()
NoteFrame = NotebookFrame(username)
NoteFrame.pack()
else:
print("error")
if __name__ == "__main__":
App().mainloop()
Firstly, you should change class name from class login(Frame) to class Login(Frame).
Before fixing it, you called the login function from App, but you need to call Login class and use it.
class App:
def __init__(self, master):
notebook = ttk.Notebook(master)
notebook.pack(expand=1, fill="both")
# Frames
main = ttk.Frame(notebook)
notebook.add(main, text='Welcome Screen')
# `entry_username.get()` method is owned by the Login class,
# so you need to call from not `self(App class)` but `login(Login class)`.
login = Login(master) # Call Login class
self.userLogged = Label(main, text=login.entry_username.get())
self.userLogged.pack()
With this fix, I could call the Welcome screen.

How to replace an existing image instead of adding additional images?

This is my first time here, and I would really appreciate some help with this.
So I have some code which runs a Tkinter tab and shows 2 buttons. If you click the first one, a picture of a cat appears.
However, if you click the button again, the same picture appears again at the bottom, making there 2.
If I click the other button, titled N/A, a different picture appears. But if you click the button again, the picture duplicates.
I want to make it so that when each button is pressed, the image is replaced, not duplicated.
Here is what I have so far.
from tkinter import *
root = Tk()
class HomeClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
def FirstClick(self):
FirstPhoto = PhotoImage(file="keyboardcat.gif")
FiLabel = Label(root, image=FirstPhoto)
FiLabel.img = FirstPhoto
FiLabel.pack()
def SecondClick(self):
FirstPhoto = PhotoImage(file="donald.gif")
FiLabel = Label(root, image=FirstPhoto)
FiLabel.img = FirstPhoto
FiLabel.pack()
k = HomeClass(root)
root.mainloop()
That's becouse every time you click a button, you're calling FirstClick method which in turn creates new instance of PhotoImage class. I think it would be better to store FirstPhoto and in every FirstClick method call check if it is already has value or not.
class HomeClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
self.FirstPhoto = None
def FirstClick(self):
if self.FirstPhoto is None:
self.FirstPhoto = PhotoImage(file="ksiazka.png")
self.FiLabel = Label(root, image=self.FirstPhoto)
self.FiLabel.img = self.FirstPhoto
self.FiLabel.pack()
Try this to change SecondPhoto
def SecondClick(self):
if self.SecondPhoto is None:
self.SecondPhoto = PhotoImage(file="ksiazka.png")
self.SecondPhotoLabel = Label(root, image=self.FirstPhoto)
self.SecondPhotoLabel.img = self.SecondPhoto
self.SecondPhotoLabel.pack()
Else:
self.SecondPhotoLabel.config(image='newimage')
self.SecondPhotoLabel.update()
Note - you can declare the newImage before as you have to read it with PhotoImage and then just put the image name in the .config
In this example you have two methods FirstClick, SecondClick to display an image and two methods to clear an first and second image accordingly: clearFirstImage, clearSecondImage. You just have to add two buttons to trigger those clear methods :)
from tkinter import *
from tkFileDialog import askopenfilename
root = Tk()
class HomeClass(object):
def __init__(self, master):
self.master = master
self.frame = Frame(master)
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
self.ToggleButtonText = "Show image"
self.ToggleButton = Button(root, text=self.ToggleButtonText, bg="Grey", fg="White",
command=self.ToggleClick)
self.ToggleButton.pack(side=LEFT, fill=X)
self.FirstPhoto = None
self.FiLabel = None
self.SecondPhoto = None
self.SecondPhotoLabel = None
self.ToggleButtonPhoto = None
self.ToggleButtonPhotoLabel = None
self.frame.pack()
def FirstClick(self):
if self.FirstPhoto is None:
self.FirstPhoto = PhotoImage(file="ksiazka.png")
self.FiLabel = Label(root, image=self.FirstPhoto)
self.FiLabel.img = self.FirstPhoto
self.FiLabel.pack()
def ToggleClick(self):
if self.ToggleButtonPhoto is None:
self.ToggleButtonPhoto = PhotoImage(file="ksiazka.png")
self.ToggleButtonPhotoLabel = Label(self.frame, image=self.ToggleButtonPhoto)
self.ToggleButtonPhotoLabel.img = self.ToggleButtonPhoto
self.ToggleButtonPhotoLabel.pack()
# and set label
self.ToggleButton.config(text="Hide image")
else:
self.ToggleButton.config(text="Show image")
self.ToggleButtonPhotoLabel.destroy()
self.ToggleButtonPhotoLabel.img = None
self.ToggleButtonPhotoLabel = None
self.ToggleButtonPhoto = None
self.frame.pack()
def SecondClick(self):
filename = askopenfilename()
allowed_extensions = ['jpg', 'png']
if len(filename) > 0 and filename.split('.')[-1] in allowed_extensions:
self.SecondPhoto = PhotoImage(file=filename)
self.SecondPhotoLabel = Label(root, image=self.SecondPhoto)
self.SecondPhotoLabel.img = self.SecondPhoto
self.SecondPhotoLabel.pack()
def clearFirstImage(self):
self.FirstPhoto = None
self.FiLabel = None
def clearSecondImage(self):
self.SecondPhoto = None
self.SecondPhotoLabel = None
k = HomeClass(root)
root.mainloop()
If you want to replace an existing image, first create the label the image is displayed in, and simply reconfigure only its image option with each click. Below is an example that does that:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def download_images():
# In order to fetch the image online
try:
import urllib.request as url
except ImportError:
import urllib as url
url.urlretrieve("https://i.stack.imgur.com/57uJJ.gif", "13.gif")
url.urlretrieve("https://i.stack.imgur.com/8LThi.gif", "8.gif")
class ImageFrame(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
def __create_image_label():
def ___load_images():
self.label.images = list()
self.label.images.append(tk.PhotoImage(file="8.gif"))
self.label.images.append(tk.PhotoImage(file="13.gif"))
self.label = tk.Label(self)
___load_images()
def __create_buttons():
self.buttons = list()
for i in range(2):
self.buttons.append(tk.Button(self, text=i,
command=lambda i=i: self.replace_image(i)))
__create_image_label()
__create_buttons()
def replace_image(self, button_index):
"""
Replaces the image in label attribute based on the index of the
button pressed.
"""
self.label['image'] = self.label.images[button_index]
def _display_widgets(self):
self.label.pack()
for i in range(2):
self.buttons[i].pack(fill='x', expand=True)
if __name__ == '__main__':
#download_images() # comment out after initial run
root = tk.Tk()
frame = ImageFrame(root)
frame.pack()
tk.mainloop()

Python Tkinter - processing data entered by a user

I want to create a program in Python with Tkinter GUI, and I want it to take string inputs from a user, then I want to do some operations on these strings - in this case, I want to mix parts of two words and get a new word. How can I handle this data entered by a user and use it to receive the result? Below is my code. I couldn't find the answer to this problem and nothing I tried works.
from Tkinter import *
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Mix words")
self.pack(fill=BOTH, expand=1)
menu = Menu(self.master)
self.master.config(menu=menu)
entryLbl1 = Label(self, text="Write the first word: ")
entryLbl1.pack()
self.entrytext1 = StringVar()
Entry(self, textvariable=self.entrytext1).pack()
self.buttontext1 = StringVar()
self.buttontext1.set("OK")
Button(self, textvariable=self.buttontext1, command=self.clicked1).pack()
self.label1 = Label(self, text="")
self.label1.pack()
global user_entry1
user_entry1 = self.entrytext1.get()
entryLbl2 = Label(self, text="Write the second word: ")
entryLbl2.pack()
self.entrytext2 = StringVar()
Entry(self, textvariable=self.entrytext2).pack()
self.buttontext2 = StringVar()
self.buttontext2.set("OK")
Button(self, textvariable=self.buttontext2, command=self.clicked2).pack()
self.label2 = Label(self, text="")
self.label2.pack()
global user_entry2
user_entry2 = self.entrytext2.get()
entryLbl3 = Label(self, text="Result: ")
entryLbl3.pack()
self.buttontext3 = StringVar()
self.buttontext3.set("Result")
Button(self, textvariable=self.buttontext1, command=self.clicked3).pack()
self.label3 = Label(self, text="")
self.label3.pack()
def clicked1(self):
input = self.entrytext1.get()
self.label1.configure(text=input)
def clicked2(self):
input = self.entrytext2.get()
self.label2.configure(text=input)
def clicked3(self):
self.user_entry1 = user_entry1
self.user_entry2 = user_entry2
first2a = user_entry1[0:2]
rest_a = user_entry1[2:]
first2b = user_entry2[0:2]
rest_b = user_entry2[2:]
input = first2b + rest_a + " " + first2a + rest_b
self.label3.configure(text=input)
root = Tk()
root.iconbitmap("py.ico")
root.geometry("600x300")
app = Window(root)
root.mainloop()
You need Entry() objects.
The following will show two Entry widgets and a Button.
When the button is pressed, the contents of both of the Entry objects will be printed to the console:
import sys
# Determine if you're running Python 3
is_py_3 = sys.version[0] == '3'
# Import Tkinter for the correct version of Python
if is_py_3:
from tkinter import Button, Entry, Tk
else:
from Tkinter import Button, Entry, Tk
class GUI:
def __init__(self):
# Set up the "Root" or "Parent" of the window.
self.root = Tk()
# Set up two "Entry" widgets.
self.entry1 = Entry(self.root)
self.entry1.insert(0, "Enter something here.")
self.entry2 = Entry(self.root)
self.entry2.insert(0, "and here...")
# Set up a button to handle the event.
self.button = Button(self.root, text="CLICK ME", command=self.onClicked)
self.entry1.pack()
self.entry2.pack()
self.button.pack()
def onClicked(self):
# Print the contents of the entry widgets.
s1 = self.entry1.get()
s2 = self.entry2.get()
print(s1, s2)
app = GUI()
app.root.mainloop()

How to open a new frame from a current window in python tkinter?

class Login:
def __init__(self):
Label1 = Label(root,text = "Username")
Label2 = Label(root,text = "Password")
self.Entry1 = Entry(root)
self.Entry2 = Entry(root,show = "*")
Label1.grid(row=0)
Label2.grid(row=1)
self.Entry1.grid(row = 0,column = 1)
self.Entry2.grid(row = 1,column = 1)
root.minsize(width = 300,height = 80)
##new_window_button = Button(text="new window", command = ????)
##new_window_button.grid(columnspan = 2)
lgbutton = Button(text = "Login",command = self.ButtonClicked)
lgbutton.grid(columnspan = 2)
def ButtonClicked(self):
username = self.Entry1.get()
password = self.Entry2.get()
GetDatabase(username,password)
Currently this is what I have to create a window, however I want it to that when the new_window_button is clicked, the new page has its own widgets. I've used Toplevel before but it creates a child window without the widgets. Instead, the widgets are added to the parent window.
Judging by the comments it looks as though you are struggling with declaring the correct parent for widgets.
When a widget is declared the first parameter passed in to it is it's parent. For example:
Label(root, text="I'm in the root window.")
# ^ This is the parent
As opposed to:
Label(top, text="I'm in the top window.")
# ^ This is the parent
Please see a more fleshed out example below:
from tkinter import *
root = Tk()
top = Toplevel(root)
label1 = Label(root, text="I'm a placeholder in your root window.")
label2 = Label(top, text="I'm a placeholder in your top window.")
label1.pack()
label2.pack()
root.mainloop()
import tkinter
from tkinter import *
class LoginForm(Frame):
def __init__(self,master=None):
super().__init__(master)
self.pack()
self.createWidget()
def createWidget(self):
self.lblEmailId=Label(self,text="Email Id")
self.lblEmailId.grid(row=0,column=0)
self.varEmailid=StringVar()
self.txtEmailId=Entry(self,textvariable=self.varEmailid)
self.txtEmailId.grid(row=0,column=1)
self.txtEmailId.bind("<KeyRelease>",self.key_press)
self.lblPassword = Label(self, text="Password")
self.lblPassword.grid(row=1, column=0)
self.varPassword=StringVar()
self.txtPassword= Entry(self, textvariable=self.varPassword)
self.txtPassword.grid(row=1, column=1)
self.btnLogin=Button(self,text="Login")
self.btnLogin.grid(row=2,column=1)
self.btnLogin.bind("<Button-1>",self.btnLogin_click)
def btnLogin_click(self,event):
self.varPassword.set(self.varEmailid.get())
LoginWindow=Toplevel()
def key_press(self,event):
self.varPassword.set(self.varEmailid.get())
root=Tk()
fromLogin=LoginForm(root)
root.mainloop()

Python Tkinter: How do you create a toplevel window and destroy the previous window?

I'm making a quiz app with tkinter and i want each question in a new window, but after I create a new window i can't figure out how to destroy the previous window. Here is a rough simplified excerpt of my code:
from tkinter import *
class q1:
def __init__(self, master):
self.master = master
Label(self.master, text='What is 3 + 3?').grid()
self.option_1 = Button(self.master, text='5', command = self.incorrect)
self.option_1.grid()
self.option_2 = Button(self.master, text='6', command = self.correct)
self.option_2.grid()
def correct(self):
self.option_1.config(state=DISABLED)
self.option_2.config(state=DISABLED)
Label(self.master, text='Correct').grid()
Button(self.master, text='Next Question', command = self.nextq).grid()
def incorrect(self):
self.option_1.config(state=DISABLED)
self.option_2.config(state=DISABLED)
Label(self.master, text='Incorrect').grid()
Button(self.master, text='Next Question', command = self.nextq).grid()
def nextq(self):
q2(Toplevel(self.master))
class q2:
def __init__(self, master):
self.master = master
Label(self.master, text='Question 2').grid()
def window():
root = Tk()
q1(root)
root.mainloop()
if __name__ == '__main__':
window()
UPDATED VERSION
from Tkinter import *
import random
class Ask:
def __init__(self, parent,question,right,wrong):
self.answer=right
self.top=top=Toplevel(parent)
Label(self.top, text=question,width=25).grid()
a1=random.choice([right,wrong])
self.option_1 = Button(self.top, text=a1, width=25,command = lambda: self.check(1))
self.option_1.grid()
a2=right
if a1==right:
a2=wrong
self.option_2 = Button(self.top, text=a2, width=25, command = lambda: self.check(2))
self.option_2.grid()
def check(self,pressed):
if pressed==1:
ans=self.option_1['text']
else:
ans=self.option_2['text']
if ans==self.answer:
self.correct()
else:
self.incorrect()
def correct(self):
self.option_1.config(state=DISABLED)
self.option_2.config(state=DISABLED)
Label(self.top, text='Correct').grid()
Button(self.top, text='Next Question', command = self.top.destroy).grid()
def incorrect(self):
self.option_1.config(state=DISABLED)
self.option_2.config(state=DISABLED)
Label(self.top, text='Incorrect').grid()
Button(self.top, text='Next Question', command = self.top.destroy).grid()
class QUIZ:
def __init__(self, questionsdict):
self.root=Tk()
self.root.withdraw()
self.questions(questionsdict)
self.root.deiconify()
c=Button(self.root, text='Click me to exit', command=self.root.destroy, width=30).grid(row=2, sticky='ew')
Label(self.root, text='Quiz is Complete', width=30, background='red').grid(row=0, sticky='ew')
mainloop()
def questions(self,questionsdict):
for k in questionsdict.keys():
right=questionsdict[k][0]
wrong=questionsdict[k][1]
b=Ask(self.root, k, right,wrong )
self.root.wait_window(b.top)
put quiz questions in a dictionary in the format: {question:[correctchoice,incorrectchoice]} and use that as the parameter when calling the Question Class
questions={'What is 3+3':['6','8'], 'What is the capital of Alaska': ['Juno','Anchorage']}
QUIZ(questions)

Categories