calling function from another class in button command - python

I want to call the showallrecords1 function from the car class when I push a button in the "gett" class.
I get the error
'gett' object has no attribute 'car'
Here is the related part of my code
from tkinter import *
import tkinter as tk
import sqlite3
conn = sqlite3.connect('jadval.db')
c = conn.cursor()
class App:
def __init__(self,master):
frame = Frame(master)
frame.pack()
## bottomframe = Frame(master)
## bottomframe.pack( side = BOTTOM )
self.master=master
a= StringVar()
b= StringVar()
a1= StringVar()
b1= StringVar()
c= StringVar()
self.button = Button(frame,text="memory", command=self.ouvrir)
self.button.pack(side=LEFT)
self.button2 = Button(frame,text="report", command=self.tabluh)
self.button2.pack(side=LEFT)
self.button3 = Button(frame,text="setting", command=self.fermer)
self.button3.pack(side=LEFT)
self.button20 = Button(frame,text="calibration", command=self.cal)
self.button20.pack(side=LEFT)
self.button30 = Button(frame,text="empty weight", command=self.weighing)
self.button30.pack(side=LEFT)
def ouvrir(self):
root3=Toplevel(self.master)
mygui=records(root3)
def tabluh(self):
root4=Toplevel(self.master)
mygui2=report(root4)
def fermer(self):
root5=Toplevel(self.master)
mygui3=settting(root5)
def cal(self):
root8=Toplevel(self.master)
mygui8=cal(root8)
def weighing(self):
root9=Toplevel(self.master)
mygui9=gett(root9)
class car():#################################################### trunck manage
def __init__(self,master):
##super(car,self).__init__()
## tk.Frame.__init__(self, master)
self.master=master
## self.master.geometry('250x200+100+200')
self.master.geometry('400x300')
self.master.title('Report')
self.button28 = Button(self.master,text="create", command=self.tabluh1)
self.button28.grid(row=0, column=0)
self.button29 = Button(self.master,text="insert rec", command=self.insertar1)
self.button29.grid(row=3, column=2)
self.tyLabel1 = Label(self.master,text="driver name")
self.tyLabel1.grid(row=1, column=0)
self.disLabel1 = Label(self.master,text="trunck type")
self.disLabel1.grid(row=2, column=0)
self.pelLabel1 = Label(self.master,text="pelack")
self.pelLabel1.grid(row=3, column=0)
self.d = Entry(self.master)
self.d.grid(row=1, column=1)
self.e = Entry(self.master)
self.e.grid(row=2, column=1)
self.f = Entry(self.master)
self.f.grid(row=3, column=1)
self.connection = sqlite3.connect('jadval.db')
self.cur = self.connection.cursor()
self.dateLabel1 = Label(self.master, text="driver name", width=10)
self.dateLabel1.grid(row=4, column=0)
self.BMILabel1 = Label(self.master, text="trunck type", width=10)
self.BMILabel1.grid(row=4, column=1)
self.stateLabel1 = Label(self.master, text="pelack", width=10)
self.stateLabel1.grid(row=4, column=2)
self.showallrecords1()
def showallrecords1(self):
data1 = self.readfromdatabase1()
for index1, dat1 in enumerate(data1):
Label(self.master, text=dat1[0]).grid(row=index1+5, column=0)
Label(self.master, text=dat1[1]).grid(row=index1+5, column=1)
Label(self.master, text=dat1[2]).grid(row=index1+5, column=2)
def tabluh1(self):
c.execute('''CREATE TABLE trunmanage(id1 INTEGER,firs1 stringvar(10),las1 stringvar(10))''')
def insertar1(self):
d1=self.d.get()
e1=self.e.get()
f1=int(self.f.get())
c.execute("INSERT INTO trunmanage (id1, firs1,las1 ) VALUES (?, ?, ?)",(f1, d1, e1))
conn.commit()
self.showallrecords1()
def readfromdatabase1(self):
self.cur.execute("SELECT * FROM trunmanage")
return self.cur.fetchall()
class gett():########################################### class selecting trunck from empty weight window
def __init__(self,master):
##super(gett,self).__init__()
## tk.Frame.__init__(self, master)
self.master=master
## self.master.geometry('250x200+100+200')
self.master.geometry('200x120')
self.master.title('gett')
## obj2 = car()
## b1 = Button(master,text="button 1",command=obj2.showallrecords1)
## b1.pack()
## self.button32 = Button(text='select', command=self.master.showallrecords1)
## self.button32.pack()
self.button32 = Button(self.master,text="select trunck", command=self.car.showallrecords1);
self.button32.pack(side=LEFT)
root = Tk()
root.title("Dbase")
root.geometry('500x120')
app=App(root)
root.mainloop()

The gett class has no member called "car". You have to define it somewhere inside the class definition. I. e.:
self.car = car(master)

Related

Python tkinter cannot update a window in a while loop

I am trying to create a main screen that changes to a homepage after user logged in. If I change while loop it never prints or opens login page. Now I changed it but whenever i logged in the login def returns true but main.py keeps it as False.
main.py:
from tkinter import *
from login import LoginNP
class NP:
def __init__(self, root):
self.root = root
self.root.geometry("1350x700+0+0")
self.root.title("New Project")
self.buton = Button(text="Giriş yap", command=self.loginPage).pack(anchor=NE)
self.title_frame = Frame(borderwidth=5,height=150,width=300, relief=RIDGE)
self.title_frame.pack(anchor=N)
self.welcome_label = Label(self.title_frame, text="Hello", height=10, width=10).pack(padx=10, pady=5)
while True:
root.update_idletasks()
root.update()
if not self.checkLogin():
break
else:
pass
def checkLogin(self):
if LoginNP.loginMessage:
print("A")
return True
else:
print("B")
return False
def loginPage(self):
self.new_win = Toplevel(self.root)
self.new_obj = LoginNP(self.new_win)
self.new_win.attributes('-topmost', True)
class HomePage:
def __init__(self, root):
self.root = root
self.root.geometry("1350x700+0+0")
self.root.title("Homepage")
self.title_frame = Frame(self.root, height=500, width=300)
self.title_frame.pack(anchor=CENTER, padx=10, pady=5)
self.welcome_label = Label(self.title_frame, text="Homepage", height=10, width=10).pack(padx=10, pady=5)
if __name__ =="__main__":
root=Tk()
obj=NP(root)
root.mainloop()
I want to update my NP window with Homepage window but in while loop program not getting result from login.py
login.py:
from tkinter import *
import sqlite3
from tkinter import messagebox
con = sqlite3.connect("npdb.db")
cur = con.cursor()
class LoginNP:
def __init__(self, root):
self.root = root
self.root.geometry("350x240")
self.root.title("Login Page")
#vars
self.username_var = StringVar()
self.password_var = StringVar()
#frames
self.upper_frame = Frame(self.root, height=70)
self.upper_frame.pack(anchor=N, fill=X, padx=10, pady=5)
self.middle_frame = Frame(self.root, height=70)
self.middle_frame.pack(anchor=CENTER, fill=X, padx=10, pady=5)
self.lower_frame = Frame(self.root, height=70)
self.lower_frame.pack(anchor=S, fill=X, padx=10, pady=5)
#label&entry
self.username_label = Label(self.upper_frame, text="Username: ").pack(anchor=W, padx=10, pady=5)
self.username_entry = Entry(self.upper_frame, textvariable=self.username_var).pack(anchor=W, padx=10, pady=5, fill=X)
self.password_label = Label(self.middle_frame, text="Password: ").pack(anchor=W, padx=10, pady=5)
self.password_entry = Entry(self.middle_frame, textvariable=self.password_var, show="*").pack(anchor=W, padx=10, pady=5, fill=X)
self.login_btn = Button(self.lower_frame, text="Login", command=self.loginMessage).grid(column=0, row=0, padx=10, pady=5)
self.register_btn = Button(self.lower_frame, text="Register",command=self.register).grid(column=1, row=0, padx=205, pady=5)
#property
def login(self):
with con:
cur.execute("SELECT * FROM user_database WHERE username=:username", {'username': self.username_var.get()})
if cur.fetchone() == None:
return False
else:
cur.execute("SELECT password FROM user_database WHERE username=:username", {'username': self.username_var.get()})
`enter code here` row = cur.fetchone()
return row[0] == self.password_var.get()
def loginMessage(self):
if self.login:
messagebox.showerror(title="Approve!", message="Giriş Başarılı!")
else:
messagebox.showerror(title="Deny!", message="Kullanıcı adı veya şifre hatalı!")
self.root.destroy()
return self.login
def search(self):
with con:
cur.execute("SELECT * FROM user_database WHERE username=:username", {'username': self.username_var.get()})
return len(cur.fetchall()) < 1
def register(self):
if self.username_var.get().strip() == "" or self.password_var.get().strip() == "":
messagebox.showerror(title='Hata!', message="Lütfen boşluk bırakmayınız!")
else:
if not self.search():
messagebox.showerror(title='Hata!', message="Kullanıcı adı zaten kayıtlı.\nLütfen başka bir kullanıcı adı alınız.")
else:
cur.execute("""INSERT INTO user_database VALUES (?, ?)""", (self.username_var.get(), self.password_var.get()))
con.commit()
if __name__ =="__main__":
root=Tk()
obj=LoginNP(root)
root.mainloop()
I suspect that if LoginNP.loginMessage: in checkLogin doesn't do what you think it does.
You have imported the LoginNP class, and loginMessage is a method of this class.
So, if LoginNP.loginMessage: basically means "does the class LoginNP have a method loginMessage". To which the answer is True.
But you are not instantiating an object of type LoginNP nor calling a method on that instance.
Check this example:
In [1]: class Foo:
...: def __init__():
...: pass
...: def bar():
...: print("calling 'bar'")
...:
In [2]: if Foo.bar:
...: print(True)
...:
True
And note the absence of the printed message calling 'bar'.

Why do my grid weights not affect the layout of window

I am writing some code for a program with a GUI, and part of this is this code:
self.chatbox = Text(self.chatframe)
self.messagebox = Entry(self.sendframe, textvariable=self.message)
self.sendbutton = Button(self.sendframe, text="Send", font=self.font(12))
self.chatframe.grid_rowconfigure(0, weight=1)
self.sendframe.grid_columnconfigure(0, weight=19)
self.sendframe.grid_columnconfigure(1, weight=1)
self.chatbox.grid(row=0, column=0)
self.messagebox.grid(row=0, column=0)
self.sendbutton.grid(row=0, column=1)
self.sendframe.grid(row=1, column=0)
self.mainframe.grid_columnconfigure(0, weight=1)
self.mainframe.grid_columnconfigure(1, weight=9)
self.mainframe.grid_rowconfigure(0, weight=1)
self.menu.grid(row=0, column=0)
self.chatframe.grid(row=0, column=1)
However when I run it, it always ends up only taking up some space and not filling the screen as I would expect. Any help appreciated.
Full Code:
from tkinter import *
import tkinter.messagebox
import os
class ServerInfo():
def __init__(self):
self.network = ""
self.host = False
self.name = StringVar()
self.name.set("")
class App(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.state("zoomed")
#self.master.minsize(1200, 600)
self.master.title("Chatroom App")
self.serverinfo = ServerInfo()
self.buffer_length = 2048
self.message = StringVar()
self.message.set("")
self.mainmenu = Frame(self.master)
self.localframe = Frame(self.master)
self.publicframe = Frame(self.master)
self.mainframe = Frame(self.master)
self.chatframe = Frame(self.mainframe)
self.sendframe = Frame(self.chatframe)
self.choiceframe = Frame(self.master)
self.inputframe = Frame(self.master)
self.create_widgets()
def font(self, size):
return ("Alef", size)
def create_widgets(self):
self.title = Label(self.mainmenu, text="The Chatroom App", font=self.font(40))
self.localbutton = Button(self.mainmenu, text="Local Chatrooms", font=self.font(16), command=self.go_to_local)
self.publicbutton = Button(self.mainmenu, text="Public Chatrooms", font=self.font(16), command=self.go_to_public)
self.exitbutton = Button(self.mainmenu, text="Exit", font=self.font(16), command=self.master.destroy)
self.title.pack(fill=BOTH)
self.localbutton.pack(pady=20, fill=BOTH)
self.publicbutton.pack(pady=20, fill=BOTH)
self.exitbutton.pack(side=BOTTOM, fill=BOTH)
self.instruction = Label(self.choiceframe, text="Would you like to host a server or search for available servers", font=self.font(26))
self.hostbutton = Button(self.choiceframe, text="Host server", font=self.font(32), command=self.host_input)
self.joinbutton = Button(self.choiceframe, text="Join server", font=self.font(32), command=self.join_input)
self.backbutton = Button(self.choiceframe, text="Back", font=self.font(32), command=self.back_from_choice)
self.instruction.pack(pady=20, fill=BOTH)
self.hostbutton.pack(pady=10, fill=BOTH)
self.joinbutton.pack(pady=10, fill=BOTH)
self.backbutton.pack(pady=20, fill=BOTH)
self.instruction2 = Label(self.inputframe, text="", font=self.font(18))
self.server_input = Entry(self.inputframe, textvariable=self.serverinfo.name)
self.continuebutton = Button(self.inputframe, text="", font=self.font(28), command=self.take_input)
self.backbutton2 = Button(self.inputframe, text="Back", font=self.font(28), command=self.back_from_input)
self.instruction2.pack(pady=10, fill=BOTH)
self.server_input.pack(pady=40, fill=BOTH)
self.continuebutton.pack(pady=10, fill=BOTH)
self.backbutton2.pack(pady=20, fill=BOTH)
self.menu = Canvas(self.mainframe, bg="Black")
self.chatbox = Text(self.chatframe)
self.messagebox = Entry(self.sendframe, textvariable=self.message)
self.sendbutton = Button(self.sendframe, text="Send", font=self.font(12))
self.chatframe.grid_rowconfigure(0, weight=1)
self.sendframe.grid_columnconfigure(0, weight=19)
self.sendframe.grid_columnconfigure(1, weight=1)
self.chatbox.grid(row=0, column=0)
self.messagebox.grid(row=0, column=0)
self.sendbutton.grid(row=0, column=1)
self.sendframe.grid(row=1, column=0)
self.mainframe.grid_columnconfigure(0, weight=1)
self.mainframe.grid_columnconfigure(1, weight=9)
self.mainframe.grid_rowconfigure(0, weight=1)
self.menu.grid(row=0, column=0)
self.chatframe.grid(row=0, column=1)
self.mainmenu.pack()
def back_from_choice(self):
self.choiceframe.forget()
self.mainmenu.pack()
window.update()
def back_from_input(self):
self.inputframe.forget()
self.choiceframe.pack()
def take_input(self):
self.inputframe.forget()
self.mainframe.pack(fill=BOTH)
def go_to_local(self):
self.serverinfo.network = "local"
self.mainmenu.forget()
self.choiceframe.pack()
window.update()
def go_to_public(self):
self.serverinfo.network = "public"
tkinter.messagebox.showinfo("Message from the developer", "This feature is still under development")
def host_input(self):
self.serverinfo.host = True
self.instruction2.config(text="Type in the name of your server. When the server is created, a server ID will show in the top left. Share this to people who want to join the server")
self.continuebutton.config(text="Host Server")
self.choiceframe.forget()
self.inputframe.pack()
def join_input(self):
self.serverinfo.host = False
self.instruction2.config(text="Type in the server ID of the server you want to join")
self.continuebutton.config(text="Join Server")
self.choiceframe.forget()
self.inputframe.pack()
def host_server(self):
pass
def join_server(self):
pass
def write_message_to_screen(self, data):
print(data)
def encode_id(self, server_id):
return server_id
def decode_id(self, server_id):
return server_id
Weights only affect how grid allocates extra space once everything has been laid out, it doesn't describe the overall relative size of widgets.
You also don't seem to be using the sticky attribute, so space may be allocated to widgets but you aren't requesting that they stretch to fill the space given to them.

Set string to text in idle

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

Tkinter does not show one frame

I am trying to make a GUI for my program but I have changed my code a lot and I saw that GUI misses one frame but it was fine before.
Could anyone help me and tell why a frame with a button does not appear on the bottom?
Whole "button_part" object does not appear.
from tkinter import *
import tkinter as tk
import os
import glob
BOUNDS = ["Last week", "Last 2 weeks", "Last 3 weeks"]
class settings_part:
path_to_copy = 0
def __init__(self, master, update_func):
path_to_copy = StringVar()
settings_frame = Frame(master, background="")
settings_frame.pack(side=TOP, fill=X)
date_bound = StringVar()
date_bound.set(BOUNDS[1])
date_option = OptionMenu(settings_frame, date_bound, *BOUNDS, command=update_func)
date_option.config(background="#732c30")
date_option.config(foreground="white")
date_option.config(bd=0)
date_option.pack(side=LEFT, padx=5, pady=5)
path_to_copy.set("~/Python/usun")
box_with_path = Entry(settings_frame, textvariable=path_to_copy)
box_with_path.pack(side=RIGHT, padx=5, pady=5)
# s = path_to_copy.get()
class songs_part:
def __init__(self, master, root):
self.songs_frame = Frame(master)
self.update_songs(root.list_of_songs)
self.songs_frame.pack()
def update_songs(self, l):
for song in l:
c = Checkbutton(self.songs_frame, text=song[0], variable=song[1])
c.pack()
class button_part:
def __init__(self, master, copyFunc):
self.button_frame = Frame(master)
btn_image = PhotoImage(file="copybtn.png")
self.copy_button = Button(self.button_frame, command=copyFunc, text="Copy",
image=btn_image, highlightthickness=0, bd=0, activebackground="#732c30")
self.copy_button.pack()
class App:
def __init__(self):
root = Tk()
root.title("Copying songs")
root.geometry("500x500")
root.option_add("*Font", "Calibra")
back_image = PhotoImage(file="back.png")
self.window = Label(root, image=back_image)
self.window.pack(fill="both", expand="yes")
self.list_of_songs = list()
self.make_list_of_songs()
self.set_part = settings_part(self.window, self.update_list)
self.son_part = songs_part(self.window, self)
self.but_part = button_part(self.window, self.copy_songs)
root.mainloop()
def make_list_of_songs(self):
owd = os.getcwd()
os.chdir("/home/stanek/Music/usun")
for file in glob.glob("*.mp3"):
self.list_of_songs.append([file, tk.IntVar()])
os.chdir(owd)
def copy_songs(self):
for s in self.list_of_songs:
print(s)
def update_list(self, arg):
print("updating list with songs from " + arg)
self.son_part = songs_part(self.window, self)
if __name__ == '__main__':
App()
You never pack the button frame.

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