I try to build a student management system while this tkinter window does not show after running following code. Can someone give some advice here? This is public source code from youtube chanel.
from tkinter import *
from tkinter import ttk
class Student:
def __init__(self,root):
self.root=root
self.root.title("student management system")
self.root.geometry("1350*700+0+0")
title=Label(self.root,text="Student Management System",bd=10,relief=GROOVE,front=("time new roman",40,"bold"),bg="yellow",fg="red")
title.pack(side=TOP,fill=X)
Manage_Frame=Frame(self.root,bd=4,relief=RIDGE,bg="crimson")
Manage_Frame.place(x=20,y=70,width=450,height=560)
#========Massage Frame===============================
Manage_Frame=Frame(self.root,bd=4,relief=RIDGE,bg="crimson")
Manage_Frame.place(x=20,y=100,width=450,height=560)
m_title=Label(Manage_Frame,text="Manage Students",bg="crimson",fg="white",front=("time new roman",30,"bold"))
m_title.grid(row=0,columnspan=2,pady=10)
lbl_roll = Label(Manage_Frame, text="Roll No.", bg="crimson", fg="white",front=("time new roman", 20, "bold"))
lbl_roll.grid(row=1, colum=0, pady=10,padx=20,sticky="w")
txt_roll = Entry(Manage_Frame,front=("time new roman", 15, "bold"),bd=5,relief=GROOVE)
txt_roll.grid(row=1, colum=2, pady=10, padx=20, sticky="w")
lbl_name = Label(Manage_Frame, text="Name", bg="crimson", fg="white", front=("time new roman", 20, "bold"))
lbl_name.grid(row=1, colum=0, pady=10, padx=20, sticky="w")
txt_name = Entry(Manage_Frame, front=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_name.grid(row=2, colum=1, pady=10, padx=20, sticky="w")
lbl_Email = Label(Manage_Frame, text="Email", bg="crimson", fg="white", front=("time new roman", 20, "bold"))
lbl_Email.grid(row=1, colum=0, pady=10, padx=20, sticky="w")
txt_Email = Entry(Manage_Frame, front=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_Email.grid(row=3, colum=0, pady=10, padx=20, sticky="w")
lbl_Gender = Label(Manage_Frame, text="Gender", bg="crimson", fg="white", front=("time new roman", 20, "bold"))
lbl_Gender.grid(row=4, colum=0, pady=10, padx=20, sticky="w")
combo_Gender=ttk.Combobox(Manage_Frame,front=("times new roman",20,"bold"))
combo_Gender['values']=("Male","Female","other")
combo_Gender.grid(row=4,colum=1,padx=20,pady=10)
lbl_Contact = Label(Manage_Frame, text="Contact", bg="crimson", fg="white", front=("time new roman", 20, "bold"))
lbl_Contact.grid(row=5, colum=0, pady=10, padx=20, sticky="w")
txt_Contact = Entry(Manage_Frame, front=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_Contact.grid(row=5, colum=1, pady=10, padx=20, sticky="w")
lbl_DOB = Label(Manage_Frame, text="DOB", bg="crimson", fg="white",front=("time new roman", 20, "bold"))
lbl_DOB.grid(row=6, colum=0, pady=10, padx=20, sticky="w")
txt_Contact = Entry(Manage_Frame, front=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_Contact.grid(row=6, colum=1, pady=10, padx=20, sticky="w")
lbl_address = Label(Manage_Frame, text="Address", bg="crimson", fg="white", front=("time new roman", 20, "bold"))
lbl_address.grid(row=6, colum=0, pady=10, padx=20, sticky="w")
txt_address = Entry(Manage_Frame, front=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_address.grid(row=6, colum=1, pady=10, padx=20, sticky="w")
#=========Button Frame=========
btn_Frame=Frame(Manage_Frame,bd=4,relief=RIDGE,bg="crimson")
btn_Frame.place(x=15, y=500, width=420)
Addbtn = Button(btn_Frame,text="add",width=10).grid(row=0,column=0,padx=10,pady=10)
Updatebtn = Button(btn_Frame, text="update", width=10).grid(row=0, column=1, padx=10, pady=10)
Deletebtn = Button(btn_Frame, text="delete", width=10).grid(row=0, column=2, padx=10, pady=10)
Clearbtn = Button(btn_Frame, text="clear", width=10).grid(row=0, column=3, padx=10, pady=10)
#=========Detail Frame=========
Detail_Frame = Frame(self.root, bd=4, relief=RIDGE, bg="crimson")
Detail_Frame.place(x=500, y=100, width=800, height=580)
lbl_search = Label(Detail_Frame, text="Search By", bg="crimson", fg="white", front=("time new roman", 20, "bold"))
lbl_search.grid(row=0, colum=0, pady=10, padx=20, sticky="w")
combo_search = ttk.Combobox(Manage_Frame,width=10,front=("times new roman", 13, "bold"),state="readonly")
combo_search['values'] = ("Roll", "Name", "contact")
combo_search.grid(row=0, colum=1, padx=20, pady=10)
txt_Search = Entry(Manage_Frame,width=15, front=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_Search.grid(row=6, colum=1, pady=10, padx=20, sticky="w")
searchbtn = Button(btn_Frame, text="Search", width=10).grid(row=0, column=3, padx=10, pady=10)
showallbtn = Button(btn_Frame, text="Show All", width=10).grid(row=0, column=4, padx=10, pady=10)
#=========Table Frame=========
Table_Frame = Frame(Detail_Frame, bd=4, relief=RIDGE, bg="crimson")
Table_Frame.place(x=10, y=70, width=760, height=500)
scroll_x=Scrollbar(Table_Frame,orient=HORIZONTAL)
scroll_y = Scrollbar(Table_Frame, orient=VERTICAL)
Student_table=ttk.Treeview(Table_Frame,columns=("roll","name","email","gender","contact","dob","Address"),xscollcommand=scroll_x.set,yscollcommand=scroll_y.set)
scroll_x.pack(side=BOTTOM,fill=X)
scroll_y.pack(side=RIGHT, fill=Y)
scroll_x.config(command=Student_table.xview)
scroll_y.config(command=Student_table.xview)
Student_table.heading("roll",text="Roll")
Student_table.heading("name", text="Name")
Student_table.heading("email", text="Email")
Student_table.heading("gender", text="Gender")
Student_table.heading("Contact", text="Contact")
Student_table.heading("D.O.B", text="D.O.B")
Student_table.heading("Address", text="Address")
Student_table['show']='headings'
Student_table.pack()
root=Tk()
You have to initialize your Student object and pass root to it. Add this to the end of your code for it to run:
app=Student(root)
root.mainloop()
Your current code as is includes a lot of syntax errors that need to be fixed before running. The following should run, albeit with some visual errors:
from tkinter import *
from tkinter import ttk
class Student:
def __init__(self,root):
self.root=root
self.root.title("student management system")
self.root.geometry("1350x700")
title=Label(self.root,text="Student Management System",bd=10,relief=GROOVE,font=("time new roman",40,"bold"),bg="yellow",fg="red")
title.pack(side=TOP,fill=X)
Manage_Frame=Frame(self.root,bd=4,relief=RIDGE,bg="crimson")
Manage_Frame.place(x=20,y=70,width=450,height=560)
#========Massage Frame===============================
Manage_Frame=Frame(self.root,bd=4,relief=RIDGE,bg="crimson")
Manage_Frame.place(x=20,y=100,width=450,height=560)
m_title=Label(Manage_Frame,text="Manage Students",bg="crimson",fg="white",font=("time new roman",30,"bold"))
m_title.grid(row=0,columnspan=2,pady=10)
lbl_roll = Label(Manage_Frame, text="Roll No.", bg="crimson", fg="white",font=("time new roman", 20, "bold"))
lbl_roll.grid(row=1, column=0, pady=10,padx=20,sticky="w")
txt_roll = Entry(Manage_Frame,font=("time new roman", 15, "bold"),bd=5,relief=GROOVE)
txt_roll.grid(row=1, column=2, pady=10, padx=20, sticky="w")
lbl_name = Label(Manage_Frame, text="Name", bg="crimson", fg="white", font=("time new roman", 20, "bold"))
lbl_name.grid(row=1, column=0, pady=10, padx=20, sticky="w")
txt_name = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_name.grid(row=2, column=1, pady=10, padx=20, sticky="w")
lbl_Email = Label(Manage_Frame, text="Email", bg="crimson", fg="white", font=("time new roman", 20, "bold"))
lbl_Email.grid(row=1, column=0, pady=10, padx=20, sticky="w")
txt_Email = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_Email.grid(row=3, column=0, pady=10, padx=20, sticky="w")
lbl_Gender = Label(Manage_Frame, text="Gender", bg="crimson", fg="white", font=("time new roman", 20, "bold"))
lbl_Gender.grid(row=4, column=0, pady=10, padx=20, sticky="w")
combo_Gender=ttk.Combobox(Manage_Frame,font=("times new roman",20,"bold"))
combo_Gender['values']=("Male","Female","other")
combo_Gender.grid(row=4,column=1,padx=20,pady=10)
lbl_Contact = Label(Manage_Frame, text="Contact", bg="crimson", fg="white", font=("time new roman", 20, "bold"))
lbl_Contact.grid(row=5, column=0, pady=10, padx=20, sticky="w")
txt_Contact = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_Contact.grid(row=5, column=1, pady=10, padx=20, sticky="w")
lbl_DOB = Label(Manage_Frame, text="DOB", bg="crimson", fg="white",font=("time new roman", 20, "bold"))
lbl_DOB.grid(row=6, column=0, pady=10, padx=20, sticky="w")
txt_Contact = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_Contact.grid(row=6, column=1, pady=10, padx=20, sticky="w")
lbl_address = Label(Manage_Frame, text="Address", bg="crimson", fg="white", font=("time new roman", 20, "bold"))
lbl_address.grid(row=6, column=0, pady=10, padx=20, sticky="w")
txt_address = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_address.grid(row=6, column=1, pady=10, padx=20, sticky="w")
#=========Button Frame=========
btn_Frame=Frame(Manage_Frame,bd=4,relief=RIDGE,bg="crimson")
btn_Frame.place(x=15, y=500, width=420)
Addbtn = Button(btn_Frame,text="add",width=10).grid(row=0,column=0,padx=10,pady=10)
Updatebtn = Button(btn_Frame, text="update", width=10).grid(row=0, column=1, padx=10, pady=10)
Deletebtn = Button(btn_Frame, text="delete", width=10).grid(row=0, column=2, padx=10, pady=10)
Clearbtn = Button(btn_Frame, text="clear", width=10).grid(row=0, column=3, padx=10, pady=10)
#=========Detail Frame=========
Detail_Frame = Frame(self.root, bd=4, relief=RIDGE, bg="crimson")
Detail_Frame.place(x=500, y=100, width=800, height=580)
lbl_search = Label(Detail_Frame, text="Search By", bg="crimson", fg="white", font=("time new roman", 20, "bold"))
lbl_search.grid(row=0, column=0, pady=10, padx=20, sticky="w")
combo_search = ttk.Combobox(Manage_Frame,width=10,font=("times new roman", 13, "bold"),state="readonly")
combo_search['values'] = ("Roll", "Name", "contact")
combo_search.grid(row=0, column=1, padx=20, pady=10)
txt_Search = Entry(Manage_Frame,width=15, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_Search.grid(row=6, column=1, pady=10, padx=20, sticky="w")
searchbtn = Button(btn_Frame, text="Search", width=10).grid(row=0, column=3, padx=10, pady=10)
showallbtn = Button(btn_Frame, text="Show All", width=10).grid(row=0, column=4, padx=10, pady=10)
#=========Table Frame=========
Table_Frame = Frame(Detail_Frame, bd=4, relief=RIDGE, bg="crimson")
Table_Frame.place(x=10, y=70, width=760, height=500)
scroll_x=Scrollbar(Table_Frame,orient=HORIZONTAL)
scroll_y = Scrollbar(Table_Frame, orient=VERTICAL)
Student_table=ttk.Treeview(Table_Frame,columns=("roll","name","email","gender","contact","dob","Address"),xscrollcommand=scroll_x.set,yscrollcommand=scroll_y.set)
scroll_x.pack(side=BOTTOM,fill=X)
scroll_y.pack(side=RIGHT, fill=Y)
scroll_x.config(command=Student_table.xview)
scroll_y.config(command=Student_table.xview)
Student_table.heading("roll",text="Roll")
Student_table.heading("name", text="Name")
Student_table.heading("email", text="Email")
Student_table.heading("gender", text="Gender")
Student_table.heading("contact", text="Contact")
Student_table.heading("dob", text="D.O.B")
Student_table.heading("Address", text="Address")
Student_table['show']='headings'
Student_table.pack()
root=Tk()
app=Student(root)
root.mainloop()
Related
I am new to Python and would like to implement a simple Employee Management System (as shown on the attached photo) that do the following functionality
• A GUI for entering, viewing, and exporting employee data. (I have done this task)
• The ability to export data into an Excel or csv file. (I have done this task)
• The ability to import data from an Excel or csv file into the GUI.
• The ability to edit employee data on screen and save the updated result to a file
I need to implement the last two tasks (i.e., import data from an CSV file and display on the GUI Window rather than on the Python Console) as my current code load the CSV file content into the Python console .
Moreover, I would like to edit the employee data on the GUI screen and save the updated result to the csv file.
Here is my code
from csv import *
from tkinter import *
from tkinter import filedialog
import tkinter.messagebox
root = Tk()
root.title("Employee Management System")
root.geometry("700x350")
root.maxsize(width=700, height=350)
root.minsize(width=700, height=350)
root.configure(background="dark gray")
# Define Variables
main_lst=[]
def OpenFile():
filepath=filedialog.askopenfilename()
# print(filepath)
# OR
file=open(filepath,'r')
print(file.read())
file.close
def Add():
lst=[txtFullname.get(),txtAddress.get(),txtAge.get(),txtPhoneNumber.get(),txtGender.get()]
main_lst.append(lst)
messagebox.showinfo("Information","The data has been added successfully")
def Save():
with open("data_entry.csv","w") as file:
Writer=writer(file)
Writer.writerow(["txtFullname","txtAddress","txtAge","txtPhoneNumber","txtGender"])
Writer.writerows(main_lst)
messagebox.showinfo("Information","Saved succesfully")
def Clear():
txtFullname.delete(0,END)
txtAddress.delete(0,END)
txtAge.delete(0,END)
txtPhoneNumber.delete(0,END)
txtGender.delete(0,END)
def Exit():
wayOut = tkinter.messagebox.askyesno("Employee Management System", "Do you want to exit the
system")
if wayOut > 0:
root.destroy()
return
# Label Widget
labelFN = Label( root,text="Full Name", font=('arial', 12, 'bold'), bd=10, fg="white",
bg="dark blue").grid(row=1, column=0)
labelAdd = Label(root, text="Home Address", font=('arial', 12, 'bold'), bd=10, fg="white",
bg="dark blue").grid(row=2, column=0)
labelAge = Label( root,text="Age", font=('arial', 12, 'bold'), bd=10, fg="white", bg="dark
blue").grid(row=3, column=0)
labelPhone_Num = Label( root, text="Phone Number", font=('arial', 12, 'bold'), bd=10,
fg="white", bg="dark blue").grid(row=4, column=0)
labelGender = Label( text="Gender", font=('arial', 12, 'bold'), bd=10, fg="white", bg="dark
blue").grid(row=5, column=0)
# Entry Widget
txtFullname = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtFullname.grid(row=1, column=1)
txtAddress = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtAddress.grid(row=2, column=1)
txtAge = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtAge.grid(row=3, column=1)
txtPhoneNumber = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtPhoneNumber.grid(row=4, column=1)
txtGender = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtGender.grid(row=5, column=1)
# Buttons
ButtonLoad = Button(text='LoadFile', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'),
width=8, fg="black",bg="dark gray", command=OpenFile).grid(row=6, column=0)
ButtonAdd = Button( text='Add Record', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'),
width=8, fg="black", bg="dark gray", command=Add).grid(row=6, column=1)
ButtonSave = Button(text='Save', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'), width=8,
fg="black", bg="dark gray", command=Save).grid(row=6, column=2)
ButtonClear = Button(text='Clear', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'), width=8,
fg="black", bg="dark gray", command=Clear).grid(row=6, column=3)
ButtonExit = Button(text='Exit', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'), width=8,
fg="black",bg="dark gray", command=Exit).grid(row=6, column=4)
'''
ButtonImport = Button(text='Import', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'),
width=8, fg="black",bg="dark gray", command=Import).grid(row=6, column=5)
'''
root.mainloop()
Employee Management System-Screenshot of the current output
In order to import data from a csv file you can use the reader method from the csv module and simply load that information into your main_lst list through your OpenFile function. I am not sure about editing though since your UI can only show one entry at a time, it makes it difficult to know which entry you are trying to edit.
from csv import *
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
root = Tk()
root.title("Employee Management System")
root.geometry("700x350")
root.maxsize(width=700, height=350)
root.minsize(width=700, height=350)
root.configure(background="dark gray")
# Define Variables
main_lst=[]
def OpenFile():
filepath=filedialog.askopenfilename()
with open(filepath, "rt") as csvfile:
rows = reader(csvfile)
for row in rows:
main_lst.append(row)
lst = [txtFullname, txtAddress, txtAge, txtPhoneNumber, txtGender]
for i,x in enumerate(lst):
x.insert(0, row[i])
def Add():
lst=[txtFullname.get(),txtAddress.get(),txtAge.get(),txtPhoneNumber.get(),txtGender.get()]
main_lst.append(lst)
messagebox.showinfo("Information","The data has been added successfully")
def Save():
with open("data_entry.csv","w") as file:
Writer=writer(file)
Writer.writerow(["txtFullname","txtAddress","txtAge","txtPhoneNumber","txtGender"])
Writer.writerows(main_lst)
messagebox.showinfo("Information","Saved succesfully")
def Clear():
txtFullname.delete(0,END)
txtAddress.delete(0,END)
txtAge.delete(0,END)
txtPhoneNumber.delete(0,END)
txtGender.delete(0,END)
def Exit():
wayOut = messagebox.askyesno("Employee Management System", "Do you want to exit the system")
if wayOut > 0:
root.destroy()
return
# Label Widget
labelFN = Label( root,text="Full Name", font=('arial', 12, 'bold'), bd=10, fg="white", bg="dark blue").grid(row=1, column=0)
labelAdd = Label(root, text="Home Address", font=('arial', 12, 'bold'), bd=10, fg="white", bg="dark blue").grid(row=2, column=0)
labelAge = Label( root,text="Age", font=('arial', 12, 'bold'), bd=10, fg="white", bg="dark blue").grid(row=3, column=0)
labelPhone_Num = Label( root, text="Phone Number", font=('arial', 12, 'bold'), bd=10, fg="white", bg="dark blue").grid(row=4, column=0)
labelGender = Label( text="Gender", font=('arial', 12, 'bold'), bd=10, fg="white", bg="dark blue").grid(row=5, column=0)
# Entry Widget
txtFullname = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtFullname.grid(row=1, column=1)
txtAddress = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtAddress.grid(row=2, column=1)
txtAge = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtAge.grid(row=3, column=1)
txtPhoneNumber = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtPhoneNumber.grid(row=4, column=1)
txtGender = Entry(root, font=('arial', 12, 'bold'), bd=4, width=22, justify='left')
txtGender.grid(row=5, column=1)
# Buttons
ButtonLoad = Button(text='LoadFile', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'), width=8, fg="black",bg="dark gray", command=OpenFile).grid(row=6, column=0)
ButtonAdd = Button( text='Add Record', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'), width=8, fg="black", bg="dark gray", command=Add).grid(row=6, column=1)
ButtonSave = Button(text='Save', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'), width=8, fg="black", bg="dark gray", command=Save).grid(row=6, column=2)
ButtonClear = Button(text='Clear', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'), width=8, fg="black", bg="dark gray", command=Clear).grid(row=6, column=3)
ButtonExit = Button(text='Exit', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'), width=8, fg="black",bg="dark gray", command=Exit).grid(row=6, column=4)
'''
ButtonImport = Button(text='Import', padx=10, pady=8, bd=4, font=('arial', 12, 'bold'),
width=8, fg="black",bg="dark gray", command=Import).grid(row=6, column=5)
'''
root.mainloop()
your csv file should look like this:
example.csv
txtFullname,txtAddress,txtAge,txtPhoneNumber,txtGender
Bob,Main St.,35,18004438768,Male
Alice,1st St.,62,922-333-1253,Female
I started with python a month ago and I'm practicing different stuff. Right now I'm building a calculator and I'm adding a day/night mode switch on menubar. That was easy. But I'd like my menubar to show only "day mode" option when it's on night mode, and viceversa.
Tried a couple of things (like use a variable for the "add_command" and then try to do "variable.config()") but didn't work. Can such thing be done?
I hope I've explained myself good enough. Sorry if my english is not quite good. Here is a piece of the code:
def mododia():
seguro=messagebox.askquestion("Blah blah", "Blah blah blah")
if seguro=="yes":
File.config(background="white", fg="blue")
Edit.config(background="white", fg="blue")
Help.config(background="white", fg="blue")
[...]
def modonoche():
messagebox.showinfo("Blah blah", "Blah blah blah")
File.config(background="black", fg="orange")
Edit.config(background="black", fg="orange")
Help.config(background="black", fg="orange")
[...]
Edit=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Edit", menu=Edit)
Edit.add_command(label="Modo día", command=mododia)
Edit.add_command(label="Modo noche", command=modonoche)
Edit to add a reproducible example:
from tkinter import *
from tkinter import messagebox
root=Tk()
root.resizable(width=0, height=0)
def mododia():
seguro=messagebox.askquestion("Activar modo día", "Se recomienda no utilizar este modo con poca luz. ¿Está seguro de querer activar el modo día?")
if seguro=="yes":
File.config(background="white", fg="blue")
Edit.config(background="white", fg="blue")
Help.config(background="white", fg="blue")
frame1.config(bg="white")
frame2.config(bg="white")
previous.config(bg="white")
previouseq.config(bg="white")
display.config(bg="white", fg="black")
current.config(bg="white")
butclear.config(bg="white", fg="blue")
butdelete.config(bg="white", fg="blue")
butpercen.config(bg="white", fg="blue")
butdivide.config(bg="white", fg="blue")
but7.config(bg="white", fg="black")
but8.config(bg="white", fg="black")
but9.config(bg="white", fg="black")
butmulti.config(bg="white", fg="blue")
but4.config(bg="white", fg="black")
but5.config(bg="white", fg="black")
but6.config(bg="white", fg="black")
butsubs.config(bg="white", fg="blue")
but1.config(bg="white", fg="black")
but2.config(bg="white", fg="black")
but3.config(bg="white", fg="black")
butadd.config(bg="white", fg="blue")
butpotency.config(bg="white", fg="blue")
but0.config(bg="white", fg="black")
butdot.config(bg="white", fg="black")
butequal.config(bg="blue", fg="white")
root.config(bg="white")
def modonoche():
messagebox.showinfo("Activar modo noche", "Esta es la configuración recomendada por el creador del programa.")
File.config(background="black", fg="orange")
Edit.config(background="black", fg="orange")
Help.config(background="black", fg="orange")
frame1.config(bg="black")
frame2.config(bg="black")
previous.config(bg="black")
previouseq.config(bg="black")
display.config(bg="black", fg="white")
current.config(bg="black")
butclear.config(bg="black", fg="orange")
butdelete.config(bg="black", fg="orange")
butpercen.config(bg="black", fg="orange")
butdivide.config(bg="black", fg="orange")
but7.config(bg="black", fg="white")
but8.config(bg="black", fg="white")
but9.config(bg="black", fg="white")
butmulti.config(bg="black", fg="orange")
but4.config(bg="black", fg="white")
but5.config(bg="black", fg="white")
but6.config(bg="black", fg="white")
butsubs.config(bg="black", fg="orange")
but1.config(bg="black", fg="white")
but2.config(bg="black", fg="white")
but3.config(bg="black", fg="white")
butadd.config(bg="black", fg="orange")
butpotency.config(bg="black", fg="orange")
but0.config(bg="black", fg="white")
butdot.config(bg="black", fg="white")
butequal.config(bg="orange", fg="white")
root.config(bg="black")
def helpme():
ayuda=messagebox.showinfo("Ayuda", "Pulse las cifras con las que desea operar y las operaciones a realizar como en una calculadora corriente.")
def about():
acercade=messagebox.showinfo("Calculadora 1.0", "Primera versión de calculadora creada por Shinington.")
def exit():
salir=messagebox.askquestion("Cerrar calculadora", "¿Seguro que desea salir?")
if salir=="yes":
root.destroy()
def erase():
inputdis.set(0)
inputcurr.set(0)
def new():
erase()
inputprev.set(0)
inputpreq.set(0)
tools=Menu(root)
File=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="File", menu=File)
File.add_command(label="Nuevo", command=new)
File.add_command(label="Borrar", command=erase)
File.add_separator()
File.add_command(label="Salir", command=exit)
Edit=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Edit", menu=Edit)
Edit.add_command(label="Modo día", command=mododia)
Edit.add_command(label="Modo noche", command=modonoche)
Help=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Help", menu=Help)
Help.add_command(label="Ayuda", command=helpme)
Help.add_command(label="Acerca de...", command=about)
root.config(bg="black", menu=tools)
frame1=Frame(root)
frame1.pack()
frame2=Frame(root)
frame2.pack()
frame1.config(bg="black", width=40, height=30)
frame2.config(bg="black", width=40, height=60)
inputdis=IntVar()
inputprev=IntVar()
inputpreq=IntVar()
inputcurr=IntVar()
previous=Entry(frame1, textvariable=inputprev)
previous.grid(row=0, column=0, sticky="e")
previous.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
previouseq=Entry(frame1, textvariable=inputpreq)
previouseq.grid(row=1, column=0, sticky="e")
previouseq.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
display=Entry(frame1, textvariable=inputdis)
display.grid(row=2, column=0, pady=10, sticky="e")
display.config(fg="white", bg="black", font=("", 12, "bold"), width=30, justify="right", borderwidth=0)
current=Entry(frame1, textvariable=inputcurr)
current.grid(row=3, column=0, pady=10, sticky="e")
current.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
butclear=Button(frame2, text="AC", width=7)
butclear.grid(row=0, column=0, padx=5, pady=10)
butclear.config(fg="orange", bg="black", font=("", 9, "bold"), borderwidth=0)
butdelete=Button(frame2, text="DEL", width=7)
butdelete.grid(row=0, column=1, padx=5, pady=10)
butdelete.config(fg="orange", bg="black", font=("", 9, "bold"), borderwidth=0)
butpercen=Button(frame2, text="%", width=7)
butpercen.grid(row=0, column=2, padx=5, pady=10)
butpercen.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
butdivide=Button(frame2, text=r"/", width=7)
butdivide.grid(row=0, column=3, padx=5, pady=10)
butdivide.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but7=Button(frame2, text="7", width=7)
but7.grid(row=1, column=0, padx=5, pady=10)
but7.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but8=Button(frame2, text="8", width=7)
but8.grid(row=1, column=1, padx=5, pady=10)
but8.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but9=Button(frame2, text="9", width=7)
but9.grid(row=1, column=2, padx=5, pady=10)
but9.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butmulti=Button(frame2, text="x", width=7)
butmulti.grid(row=1, column=3, padx=5, pady=10)
butmulti.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but4=Button(frame2, text="4", width=7)
but4.grid(row=2, column=0, padx=5, pady=10)
but4.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but5=Button(frame2, text="5", width=7)
but5.grid(row=2, column=1, padx=5, pady=10)
but5.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but6=Button(frame2, text="6", width=7)
but6.grid(row=2, column=2, padx=5, pady=10)
but6.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butsubs=Button(frame2, text="-", width=7)
butsubs.grid(row=2, column=3, padx=5, pady=10)
butsubs.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but1=Button(frame2, text="1", width=7)
but1.grid(row=3, column=0, padx=5, pady=10)
but1.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but2=Button(frame2, text="2", width=7)
but2.grid(row=3, column=1, padx=5, pady=10)
but2.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but3=Button(frame2, text="3", width=7)
but3.grid(row=3, column=2, padx=5, pady=10)
but3.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butadd=Button(frame2, text="+", width=7)
butadd.grid(row=3, column=3, padx=5, pady=10)
butadd.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
butpotency=Button(frame2, text="x^", width=7)
butpotency.grid(row=4, column=0, padx=5, pady=10)
butpotency.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but0=Button(frame2, text="0", width=7)
but0.grid(row=4, column=1, padx=5, pady=10)
but0.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butdot=Button(frame2, text=".", width=7)
butdot.grid(row=4, column=2, padx=5, pady=10)
butdot.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butequal=Button(frame2, text="=", width=7)
butequal.grid(row=4, column=3, padx=5, pady=10)
butequal.config(fg="white", bg="orange", font=("", 10, "bold"), borderwidth=0)
root.mainloop()
There you can switch between "modo día" (day mode) and "modo noche" (night mode), but I'd like that only one of the options is available on the menu bar (night mode when day mode is selected and viceversa).
I don't want it to change automatically as time goes on, but to manually change it with the menubar. Can that be done with the entryconfigure that Bryan Oakley talks about? I don't know about the Flags Cool Cloud mention either. As I said, I've started programming a few weeks ago.
Delete this line:
Edit.add_command(label="Modo noche", command=modonoche)
Add these two line to your code:
def modonoche():
...
Edit.entryconfigure(0,label='mododia',command=mododia)
def mododia():
seguro=messagebox.askquestion("Activar modo día", "Se recomienda no utilizar este modo con poca luz. ¿Está seguro de querer activar el modo día?")
if seguro=="yes":
...
Edit.entryconfigure(0,label='modonoche',command=modonoche)
Source:
http://tcl.tk/man/tcl8.5/TkCmd/menu.htm#M55
This is your code with the modifications you want
from tkinter import *
from tkinter import messagebox
root=Tk()
root.resizable(width=0, height=0)
def mododia(): #Lite Mode
seguro=messagebox.askquestion("Activar modo día", "Se recomienda no utilizar este modo con poca luz. ¿Está seguro de querer activar el modo día?")
Edit.entryconfig(1,label = "Modo noche" , command = modonoche)
if seguro=="yes":
File.config(background="white", fg="blue")
Edit.config(background="white", fg="blue")
Help.config(background="white", fg="blue")
frame1.config(bg="white")
frame2.config(bg="white")
previous.config(bg="white")
previouseq.config(bg="white")
display.config(bg="white", fg="black")
current.config(bg="white")
butclear.config(bg="white", fg="blue")
butdelete.config(bg="white", fg="blue")
butpercen.config(bg="white", fg="blue")
butdivide.config(bg="white", fg="blue")
but7.config(bg="white", fg="black")
but8.config(bg="white", fg="black")
but9.config(bg="white", fg="black")
butmulti.config(bg="white", fg="blue")
but4.config(bg="white", fg="black")
but5.config(bg="white", fg="black")
but6.config(bg="white", fg="black")
butsubs.config(bg="white", fg="blue")
but1.config(bg="white", fg="black")
but2.config(bg="white", fg="black")
but3.config(bg="white", fg="black")
butadd.config(bg="white", fg="blue")
butpotency.config(bg="white", fg="blue")
but0.config(bg="white", fg="black")
butdot.config(bg="white", fg="black")
butequal.config(bg="blue", fg="white")
root.config(bg="white")
def modonoche(): #Dark Mode
messagebox.showinfo("Activar modo noche", "Esta es la configuración recomendada por el creador del programa.")
Edit.entryconfig(1,label = "Modo dia" , command = mododia)
File.config(background="black", fg="orange")
Edit.config(background="black", fg="orange")
Help.config(background="black", fg="orange")
frame1.config(bg="black")
frame2.config(bg="black")
previous.config(bg="black")
previouseq.config(bg="black")
display.config(bg="black", fg="white")
current.config(bg="black")
butclear.config(bg="black", fg="orange")
butdelete.config(bg="black", fg="orange")
butpercen.config(bg="black", fg="orange")
butdivide.config(bg="black", fg="orange")
but7.config(bg="black", fg="white")
but8.config(bg="black", fg="white")
but9.config(bg="black", fg="white")
butmulti.config(bg="black", fg="orange")
but4.config(bg="black", fg="white")
but5.config(bg="black", fg="white")
but6.config(bg="black", fg="white")
butsubs.config(bg="black", fg="orange")
but1.config(bg="black", fg="white")
but2.config(bg="black", fg="white")
but3.config(bg="black", fg="white")
butadd.config(bg="black", fg="orange")
butpotency.config(bg="black", fg="orange")
but0.config(bg="black", fg="white")
butdot.config(bg="black", fg="white")
butequal.config(bg="orange", fg="white")
root.config(bg="black")
def helpme():
ayuda=messagebox.showinfo("Ayuda", "Pulse las cifras con las que desea operar y las operaciones a realizar como en una calculadora corriente.")
def about():
acercade=messagebox.showinfo("Calculadora 1.0", "Primera versión de calculadora creada por Shinington.")
def exit():
salir=messagebox.askquestion("Cerrar calculadora", "¿Seguro que desea salir?")
if salir=="yes":
root.destroy()
def erase():
inputdis.set(0)
inputcurr.set(0)
def new():
erase()
inputprev.set(0)
inputpreq.set(0)
tools=Menu(root)
File=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="File", menu=File)
File.add_command(label="Nuevo", command=new)
File.add_command(label="Borrar", command=erase)
File.add_separator()
File.add_command(label="Salir", command=exit)
Edit=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Edit", menu=Edit)
Edit.add_command(label="Modo día", command=mododia)
Help=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Help", menu=Help)
Help.add_command(label="Ayuda", command=helpme)
Help.add_command(label="Acerca de...", command=about)
root.config(bg="black", menu=tools)
frame1=Frame(root)
frame1.pack()
frame2=Frame(root)
frame2.pack()
frame1.config(bg="black", width=40, height=30)
frame2.config(bg="black", width=40, height=60)
inputdis=IntVar()
inputprev=IntVar()
inputpreq=IntVar()
inputcurr=IntVar()
previous=Entry(frame1, textvariable=inputprev)
previous.grid(row=0, column=0, sticky="e")
previous.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
previouseq=Entry(frame1, textvariable=inputpreq)
previouseq.grid(row=1, column=0, sticky="e")
previouseq.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
display=Entry(frame1, textvariable=inputdis)
display.grid(row=2, column=0, pady=10, sticky="e")
display.config(fg="white", bg="black", font=("", 12, "bold"), width=30, justify="right", borderwidth=0)
current=Entry(frame1, textvariable=inputcurr)
current.grid(row=3, column=0, pady=10, sticky="e")
current.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
butclear=Button(frame2, text="AC", width=7)
butclear.grid(row=0, column=0, padx=5, pady=10)
butclear.config(fg="orange", bg="black", font=("", 9, "bold"), borderwidth=0)
butdelete=Button(frame2, text="DEL", width=7)
butdelete.grid(row=0, column=1, padx=5, pady=10)
butdelete.config(fg="orange", bg="black", font=("", 9, "bold"), borderwidth=0)
butpercen=Button(frame2, text="%", width=7)
butpercen.grid(row=0, column=2, padx=5, pady=10)
butpercen.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
butdivide=Button(frame2, text=r"/", width=7)
butdivide.grid(row=0, column=3, padx=5, pady=10)
butdivide.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but7=Button(frame2, text="7", width=7)
but7.grid(row=1, column=0, padx=5, pady=10)
but7.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but8=Button(frame2, text="8", width=7)
but8.grid(row=1, column=1, padx=5, pady=10)
but8.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but9=Button(frame2, text="9", width=7)
but9.grid(row=1, column=2, padx=5, pady=10)
but9.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butmulti=Button(frame2, text="x", width=7)
butmulti.grid(row=1, column=3, padx=5, pady=10)
butmulti.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but4=Button(frame2, text="4", width=7)
but4.grid(row=2, column=0, padx=5, pady=10)
but4.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but5=Button(frame2, text="5", width=7)
but5.grid(row=2, column=1, padx=5, pady=10)
but5.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but6=Button(frame2, text="6", width=7)
but6.grid(row=2, column=2, padx=5, pady=10)
but6.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butsubs=Button(frame2, text="-", width=7)
butsubs.grid(row=2, column=3, padx=5, pady=10)
butsubs.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but1=Button(frame2, text="1", width=7)
but1.grid(row=3, column=0, padx=5, pady=10)
but1.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but2=Button(frame2, text="2", width=7)
but2.grid(row=3, column=1, padx=5, pady=10)
but2.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but3=Button(frame2, text="3", width=7)
but3.grid(row=3, column=2, padx=5, pady=10)
but3.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butadd=Button(frame2, text="+", width=7)
butadd.grid(row=3, column=3, padx=5, pady=10)
butadd.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
butpotency=Button(frame2, text="x^", width=7)
butpotency.grid(row=4, column=0, padx=5, pady=10)
butpotency.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but0=Button(frame2, text="0", width=7)
but0.grid(row=4, column=1, padx=5, pady=10)
but0.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butdot=Button(frame2, text=".", width=7)
butdot.grid(row=4, column=2, padx=5, pady=10)
butdot.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butequal=Button(frame2, text="=", width=7)
butequal.grid(row=4, column=3, padx=5, pady=10)
butequal.config(fg="white", bg="orange", font=("", 10, "bold"), borderwidth=0)
root.mainloop()
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 1 year ago.
from tkinter import *
from tkinter import ttk
from PIL import ImageTk ,Image
win=tkinter.Toplevel()
wrapper=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper.place(x=0, y=80, width=465, height=625)
wrapper3=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper3.place(x=950, y=80, width=465, height=625)
wrapper3_title=Label(wrapper3, text="Selected Data", bg="crimson", fg="white", font=("times new roman",30,"bold"))
wrapper3_title.grid(row=0,column=0,padx=20, pady=10)
wrapper2=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper2.place(x=465, y=80, width=485, height=625)
ent8=StringVar()
def code():
btn1.destroy()
add=StringVar()
sub=StringVar()
pro=StringVar()
img=ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
Label2= Label(wrapper2, image=img)
Label2.grid(row=0, column=0, padx=10, pady=5, sticky='w')
def Find():
add.set(float(ent00.get())+float(ent01.get()))
sub.set(float(ent00.get())-float(ent01.get()))
pro.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(wrapper, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(wrapper, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(wrapper, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(wrapper, textvariable=add, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(wrapper, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(wrapper, textvariable=sub, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(wrapper, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(wrapper, textvariable=pro, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(wrapper, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
def img():
if ent8.get()=="4":
img=ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
Label2= Label(wrapper3, image=img)
Label2.grid(row=0, column=2, padx=10, pady=5, sticky='w')
print("Move ahead")
else:
print("Try again")
btn2 = Button(wrapper, text = 'Image', command=img, bd = '5', width=15, height=2)
btn2.grid(row=12, column=1, padx=20, pady=10)
btn1 = Button(wrapper, text = 'OPEN CODE', command=code, bd = '5', width=20, height=2)
btn1.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
Two images need to be shown on the tkinter. The one defined earlier in wrapper2, shows empty frame while the one that has to appear in wrapper3 after getting 4 as sum, does not appear at all. Moreover, the output printed is "Try again". Why it is so? When sum is 4 it has to show "Move ahead".
First of all, terrible names.
Both your function and your PhotoImage are named img. Rename the function to def add_img().
Second, looking at your code I have no idea what all the wrapper frames are for, why not name them according to what they are planned to hold? Same applies to all the widgets. Wouldn't calc_btn be a better name than btn? img_btn instead of btn2? Why do you need to read more than the name to know what something is?
Third, you have ent8 twice in your code. Once as Label and again as a StringVar.
Tkinter constantly refreshes your window so you need to save the image you are using.
Personally I would have done all of this in a class.
For right now, with your current code, just add
loaded_img = ImageTk.PhotoImage(Image.open("Amritsar.jpg")) before your functions and instead of using the variables you are using to open the image, just use Label(wrapper3, image=loaded_img)
As in:
win = Toplevel()
wrapper=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper.place(x=0, y=80, width=465, height=625)
wrapper3=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper3.place(x=950, y=80, width=465, height=625)
wrapper3_title=Label(wrapper3, text="Selected Data", bg="crimson", fg="white", font=("times new roman",30,"bold"))
wrapper3_title.grid(row=0,column=0,padx=20, pady=10)
wrapper2=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper2.place(x=465, y=80, width=485, height=625)
ent8=StringVar()
loaded_img = ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
Edit
Here is the entire code:
from tkinter import *
from tkinter import ttk
from PIL import ImageTk ,Image
win=Toplevel()
wrapper=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper.place(x=0, y=80, width=465, height=625)
wrapper3=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper3.place(x=950, y=80, width=465, height=625)
wrapper3_title=Label(wrapper3, text="Selected Data", bg="crimson", fg="white", font=("times new roman",30,"bold"))
wrapper3_title.grid(row=0,column=0,padx=20, pady=10)
wrapper2=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper2.place(x=465, y=80, width=485, height=625)
ent8=StringVar()
loaded_img = ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
add_strvar = StringVar()
sub_strvar = StringVar()
pro_strvar = StringVar()
def code():
btn1.destroy()
Label2= Label(wrapper2, image=loaded_img)
Label2.grid(row=0, column=0, padx=10, pady=5, sticky='w')
def Find():
add_strvar.set(float(ent00.get())+float(ent01.get()))
sub_strvar.set(float(ent00.get())-float(ent01.get()))
pro_strvar.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(wrapper, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(wrapper, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(wrapper, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(wrapper, textvariable=add_strvar, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(wrapper, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(wrapper, textvariable=sub_strvar, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(wrapper, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(wrapper, textvariable=pro_strvar, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(wrapper, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
def add_img():
if add_strvar.get() == "4.0":
Label2= Label(wrapper3, image=loaded_img)
Label2.grid(row=0, column=2, padx=10, pady=5, sticky='w')
print("Move ahead")
else:
print("Try again")
btn2 = Button(wrapper, text = 'Image', command=add_img, bd = '5', width=15, height=2)
btn2.grid(row=12, column=1, padx=20, pady=10)
btn1 = Button(wrapper, text = 'OPEN CODE', command=code, bd = '5', width=20, height=2)
btn1.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
Edit 2
Code changed to work with classes:
from tkinter import *
from tkinter import ttk
from PIL import ImageTk ,Image
class ImageCalculator:
def __init__(self, img_path):
self.window = Toplevel()
self.window.geometry("1400x700+250+250")
self.mainframe = Frame(self.window)
self.mainframe.pack(expand=True, fill=BOTH)
self.bg_color = 'crimson'
frame_settings = {'master': self.mainframe, 'bd': 4,
'relief': RIDGE, 'bg': self.bg_color}
frame_names = ('left', 'center', 'right')
self.frames = {name: Frame(**frame_settings) for name in frame_names}
frame_height = 625
init_y = 80
frame_widths = {'left': 465, 'center': 485, 'right': 465}
x = 0
for name in frame_names:
frame_width = frame_widths[name]
self.frames[name].place(x=x, y=init_y, width=frame_width,
height=frame_height)
x += frame_width
self.setup_right_wrapper()
self.code_btn = self.setup_left_wrapper()
self.loaded_image = ImageTk.PhotoImage(Image.open(img_path))
self.add_strvar = StringVar()
self.sub_strvar = StringVar()
self.pro_strvar = StringVar()
def setup_left_wrapper(self) -> Button:
code_btn = Button(self.frames['left'], text='OPEN CODE', command=self.code,
bd='5', width=20, height=2)
img_btn = Button(self.frames['left'], text='Image', bd='5', width=15,
height=2, command=self.add_img)
code_btn.grid(row=11, column=1, padx=20, pady=10)
img_btn.grid(row=12, column=1, padx=20, pady=10)
return code_btn
def setup_right_wrapper(self):
right_frame_title = Label(self.frames['right'], text="Selected Data",
bg=self.bg_color, fg="white",
font=("times new roman",30,"bold"))
right_frame_title.grid(row=0, column=0, padx=20, pady=10)
def code(self):
def Find():
self.add_strvar.set(float(first_entry.get())
+ float(second_entry.get()))
self.sub_strvar.set(float(first_entry.get())
- float(second_entry.get()))
self.pro_strvar.set(float(first_entry.get())
* float(second_entry.get()))
self.code_btn.destroy()
Label2 = Label(self.frames['center'], image=self.loaded_image)
Label2.grid(row=0, column=0, padx=10, pady=5, sticky='w')
left_frame = self.frames['left']
first_entry = Entry(left_frame, width=15)
second_entry = Entry(left_frame, width=15)
# Settings of all labels
lbl_settings = {'bg': self.bg_color, 'fg': 'white',
'font': ("times new roman", 15, "bold")}
# Setting of all entry.
entry_settings = {'width': 15, 'state': 'readonly'}
add_lbl = Label(left_frame, text="Add", **lbl_settings)
add_entry = Entry(left_frame, textvariable=self.add_strvar,
**entry_settings)
sub_lbl = Label(left_frame, text="Subtract", **lbl_settings)
sub_entry = Entry(left_frame, textvariable=self.sub_strvar,
**entry_settings)
pro_lbl = Label(left_frame, text="Product", **lbl_settings)
pro_entry = Entry(left_frame, textvariable=self.pro_strvar,
**entry_settings)
calc_btn = Button(left_frame, text='Calculate', command=Find, bd='5',
width=15, height=2)
# Widget placement.
first_entry.grid(row=4, column=1, padx=10, pady=10, sticky='w')
second_entry.grid(row=5, column=1, padx=10, pady=10, sticky='w')
add_lbl.grid(row=6, column=0, padx=20, pady=10, sticky='w')
add_entry.grid(row=6, column=1, padx=10, pady=10, sticky='w')
sub_lbl.grid(row=7, column=0, padx=20, pady=10, sticky='w')
sub_entry.grid(row=7, column=1, padx=10, pady=10, sticky='w')
pro_lbl.grid(row=8, column=0, padx=20, pady=10, sticky='w')
pro_entry.grid(row=8, column=1, padx=10, pady=10, sticky='w')
calc_btn.grid(row=11, column=1, padx=20, pady=10)
def add_img(self):
if self.add_strvar.get() == "4.0":
Label2 = Label(self.frames['right'], image=self.loaded_image)
Label2.grid(row=0, column=2, padx=10, pady=5, sticky='w')
print("Move ahead")
else:
print("Try again")
def main():
img_calc = ImageCalculator('Amritsar.jpg')
mainloop()
if __name__ == "__main__":
main()
After setting an image for a Label, you need to keep a reference to this image. Otherwise, it's removed at the end of the function and you lose the image (it's garbage collected).
So, when you define your label, just add a line that stores the image as an attribute of the label:
img=ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
Label2= Label(wrapper2, image=img)
Label2.grid(row=0, column=0, padx=10, pady=5, sticky='w')
Label2.dontloseit = img
The Label2 widget now has a nonsensical attribute called .dontloseit which holds the image. Now, it won't get collected and it will show in your tkinter widget.
It's one of the peculiarities of tkinter.
The 1st code completely works fine.
1st Code
from tkinter import *
from tkinter import ttk
win=Tk()
add=StringVar()
sub=StringVar()
pro=StringVar()
def Find():
add.set(float(ent00.get())+float(ent01.get()))
sub.set(float(ent00.get())-float(ent01.get()))
pro.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(win, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(win, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(win, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(win, textvariable=add, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(win, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(win, textvariable=sub, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(win, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(win, textvariable=pro, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(win, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
But when I define it i.e. make it a function (As in the code below), it doesn't work. Also it doesn't even show any error. I am not understanding the reason for this issue.
2nd Code:
from tkinter import *
from tkinter import ttk
win=Tk()
def code():
win=Tk()
add=StringVar()
sub=StringVar()
pro=StringVar()
def Find():
add.set(float(ent00.get())+float(ent01.get()))
sub.set(float(ent00.get())-float(ent01.get()))
pro.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(win, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(win, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(win, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(win, textvariable=add, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(win, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(win, textvariable=sub, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(win, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(win, textvariable=pro, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(win, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
btn1 = Button(win, text = 'OPEN CODE', command=code, bd = '5', width=20, height=2)
btn1.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
Is there any kind of mistake I am doing leading to its non-working? ______________________
You are redefining win and then performing actions on that, which doesn't seem to play nice together. If you want to clear the screen and place new widgets, here's how I would do it:
from tkinter import *
from tkinter import ttk
win=Tk()
def code():
btn1.destroy()
add=StringVar()
sub=StringVar()
pro=StringVar()
def Find():
add.set(float(ent00.get())+float(ent01.get()))
sub.set(float(ent00.get())-float(ent01.get()))
pro.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(win, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(win, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(win, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(win, textvariable=add, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(win, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(win, textvariable=sub, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(win, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(win, textvariable=pro, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(win, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
btn1 = Button(win, text = 'OPEN CODE', command=code, bd = '5', width=20, height=2)
btn1.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
I just removed the three lines modifying win in the code function and added btn1.destroy(), which removes the button we want to stop displaying from the window.
I have my main code using the withdraw and deiconify commands which work. When i apply them to different functions (which dont affect the main code), they dont seem to work.
I get the following error:
homeButton = Button(content, width=50, height=50, command=lambda:[homePage.deiconify(), resourcePage.destroy()])
AttributeError: 'function' object has no attribute 'deiconify'
Ive taken a small piece of relevant code from my code so you can test it if you would like
Just click submit button on the first page, click the resources button on the next page, and the home button in the top left of the page will be the one that is not working how it should be
from tkinter import *
def resourcePage():
global homeIcon
global file
resource = Toplevel()
resource.title("Resource Page")
resource.resizable(0, 0)
header = LabelFrame(resource, bg="white")
content = LabelFrame(resource, bg="white")
header.columnconfigure(0, weight=1) # Forces column to expand to fill all available space
homeButton = Button(content, width=50, height=50, command=lambda:[homePage.deiconify(), resourcePage.destroy()])
#HERE IS THE ERROR ^^
try:
homeIcon = PhotoImage(file="yes.png")
homeButton.config(image=homeIcon)
homeButton.image = homeIcon
except TclError:
print("Home")
homeButton.grid(row=1, column=0, sticky="w", padx=2, pady=2)
# each section of code below is for their respective labels on the page
papersLabel = Label(content, text="Exam Papers", bg="#12a8e3", fg="white", font=("Ariel", 26, "bold"),
activebackground="#12a8e3", anchor="w", padx=15)
papersLabel.grid(row=2, column=0, padx=15, pady=(15, 5), ipadx=429, ipady=10)
papersPhysics = Label(content, text="Physics:", bg="white", font=("Ariel", 22), anchor="w")
papersPhysics.grid(row=3, column=0, sticky="w", padx=20)
papersHyperlinks = Label(content, text="• Hyperlinks here", bg="white", font=("Ariel", 18), anchor="w")
papersHyperlinks.grid(row=4, column=0, sticky="w", padx=24)
papersCS = Label(content, text="Computer Science:", bg="white", font=("Ariel", 22), anchor="w")
papersCS.grid(row=5, column=0, sticky="w", padx=20)
papersHyperlinks = Label(content, text="• Hyperlinks here", bg="white", font=("Ariel", 18), anchor="w")
papersHyperlinks.grid(row=6, column=0, sticky="w", padx=24)
questionsLabel = Label(content, text="Practice Exam Questions:", bg="#12a8e3", fg="white",
font=("Ariel", 26, "bold"), activebackground="#12a8e3", anchor="w", padx=15)
questionsLabel.grid(row=7, column=0, padx=15, pady=(25, 5), ipadx=328, ipady=10)
questionsPhysics = Label(content, text="Physics:", bg="white", font=("Ariel", 22), anchor="w")
questionsPhysics.grid(row=8, column=0, sticky="w", padx=20)
questionsHyperlinks = Label(content, text="• Hyperlinks here", bg="white", font=("Ariel", 18), anchor="w")
questionsHyperlinks.grid(row=9, column=0, sticky="w", padx=24)
questionsCS = Label(content, text="Computer Science:", bg="white", font=("Ariel", 22), anchor="w")
questionsCS.grid(row=10, column=0, sticky="w", padx=20)
questionsHyperlinks = Label(content, text="• Hyperlinks here", bg="white", font=("Ariel", 18), anchor="w")
questionsHyperlinks.grid(row=11, column=0, sticky="w", padx=24)
videosLabel = Label(content, text="Helpful Videos:", bg="#12a8e3", fg="white", font=("Ariel", 26, "bold"),
activebackground="#12a8e3", anchor="w", padx=15)
videosLabel.grid(row=12, column=0, padx=15, pady=(25, 5), ipadx=415, ipady=10)
videosPhysics = Label(content, text="Physics:", bg="white", font=("Ariel", 22), anchor="w")
videosPhysics.grid(row=13, column=0, sticky="w", padx=20)
videosHyperlinks = Label(content, text="• Hyperlinks here", bg="white", font=("Ariel", 18), anchor="w")
videosHyperlinks.grid(row=14, column=0, sticky="w", padx=24)
videosCS = Label(content, text="Computer Science:", bg="white", font=("Ariel", 22), anchor="w")
videosCS.grid(row=15, column=0, sticky="w", padx=20)
videosHyperlinks = Label(content, text="• Hyperlinks here", bg="white", font=("Ariel", 18), anchor="w")
videosHyperlinks.grid(row=16, column=0, sticky="w", padx=24,
pady=(0, 25)) # y padding here to keep some space from the bottom of the page
header.grid(row=0, sticky='NSEW')
content.grid(row=1, sticky='NSEW')
def homePage():
homePage = Toplevel()
homePage.title("Home Page")
homePage.resizable(0, 0)
header = LabelFrame(homePage, bg="#12a8e3")
content = LabelFrame(homePage, bg="white")
header.columnconfigure(0, weight=1) # Forces column to expand to fill all available space
title = Label(header, text="School Subjects Quiz", bg="#12a8e3", fg="white", font=("Ariel", 35, "bold"), padx=10,
pady=10)
title.grid(row=0, column=0, columnspan=3)
# I will add thumbnails to the buttons in later development phases
questionsButton = Button(content, text="Questions", padx=380, pady=100, bg="#12a8e3", fg="white",
font=("Ariel", 45, "bold"), activebackground="#12a8e3", command=lambda:[subjectSelection(), homePage.withdraw()])
questionsButton.grid(row=1, column=0, columnspan=3, padx=15, pady=40)
accountButton = Button(content, text="Account", padx=100, pady=135, bg="#12a8e3", fg="white",
font=("Ariel", 45, "bold"), activebackground="#12a8e3", command=lambda:[accountPage(), homePage.withdraw()])
accountButton.grid(row=2, column=0, padx=30, pady=35)
resourceButton = Button(content, text="Revision" + "\n" + "Resources", padx=100, pady=100, bg="#12a8e3", fg="white",
font=("Ariel", 45, "bold"), activebackground="#12a8e3", command=lambda:[resourcePage(), homePage.withdraw()])
resourceButton.grid(row=2, column=1, padx=30, pady=35)
header.grid(row=0, sticky='NSEW')
content.grid(row=1, sticky='NSEW')
#Creating the log in page
root = Tk()
root.title("Log-in page")
root.geometry('1000x850') #creates dimensions of page
root.resizable(0,0) #will disable max/min tab of window
#seperating the page into sections
header = LabelFrame(root, bg="#12a8e3")
content = LabelFrame(root, bg="white")
root.columnconfigure(0, weight=1) # 100%
root.rowconfigure(0, weight=2) # 2%
root.rowconfigure(1, weight=98) # 98%
#creating the title of the page to be displayed in the header
title = Label(header, text="School Subjects Quiz", bg="#12a8e3", fg="white", font=("Ariel",65, "bold"), padx=10, pady=10)
title.pack(expand=TRUE)
#username input box
usernameLabel = Label(content, width = 60, borderwidth=5, font=("Ariel", 22), text="Enter Username", bg="white", anchor="w", padx=100)
usernameLabel.pack(ipady = 8, pady=(55,0))
usernameBox = Entry(content, width = 60, borderwidth=5, font=("HelvLight", 18))
usernameBox.pack(ipady = 10)
#password input box
passwordLabel = Label(content, width = 60, borderwidth=5, font=("Ariel", 22), text="Enter Password", bg="white", anchor="w", padx=100)
passwordLabel.pack(ipady = 8, pady=(55,0))
passwordLabel = Entry(content, width = 60, borderwidth=5, font=("HelvLight", 18))
passwordLabel.pack(ipady = 10)
#submit buttons for inputs
submitButton = Button(content, width = 20, borderwidth=5, font=("Ariel", 22), text="Submit", bg="#b5b5b5", fg="black", activebackground="#b5b5b5", command=lambda:[homePage(), root.withdraw()])
submitButton.pack(ipady = 5, pady=(15,0))
#button to click on to make an account
registerButton = Button(content, width = 40, borderwidth=5, font=("Ariel", 24), text="New? Click here to register", bg="#12a8e3", fg="white", activebackground="#12a8e3", command=lambda:[register(), root.withdraw()])
#withdraw hides the window and register calls upon the register function
registerButton.pack(ipady = 20, pady=(100,0))
header.grid(row=0, sticky='news')
content.grid(row=1, sticky='news')
root.mainloop()
Comments are right, you are mixing up function names and variable names. You can solve it as follows:
Rename all HomePage variables to (for example) HomePg, except of course for the function name and the function call in submitButton.
Now you run into a second problem: HomePg is a local function variable which is unknown to the resourcePage() function. A quick way to solve it is to make it global by adding global homePg immediately after def homePage()
This solves the original error, but reveals another one: you are trying to destroy the function resourcePage() (same line as the original error). Change this to: resource.destroy().
After this, your code should be running error-free.