Open a new frame so it changes and displays a new page - python

I am trying to create a login page, when the user clicks the login button it is supposed to display a new page (not Toplevel, and create a new window), but it doesn't seem to work.
root = Tk()
root.geometry('670x466')
accounts = []
class Goode_brothers:
def __init__(self, parent):
self.myFrame = Frame(parent)
self.myFrame.pack()
self.load = Image.open('new-dip-project\\food.jpg')
self.render = ImageTk.PhotoImage(self.load)
self.img = Label(parent, image = self.render)
self.img.place(x = -26, y =0)
self.img_login = PhotoImage(file = 'new-dip-project\\button (3).png')
self.b1 = Button(parent,image = self.img_login, command = self.read_info, bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b1.place(x = 275, y = 340)
self.img_register = PhotoImage(file = 'new-dip-project\\register.png')
self.b2 = Button(parent,image = self.img_register, command = self.openNewWindow, bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b2.place(x = 265, y = 400)
self.canvas = Canvas(parent, width = 400, height = 120)
self.canvas.pack()
self.img4 = ImageTk.PhotoImage(Image.open('new-dip-project\\goode.png'))
self.canvas.create_image(20, 20, anchor=NW, image=self.img4)
self.email = Entry(parent)
self.email.place(x = 340, y = 180)
self.password = Entry(parent)
self.password.place(x = 354, y = 250)
self.img_label = PhotoImage(file = 'new-dip-project\\label-image.png')
self.name = Label(parent, image = self.img_label, text = "Email:", bg = '#3c3a3b').place(x = 197,y = 178)
self.img_label_pass = PhotoImage(file = 'new-dip-project\\label_pass.png')
self.name = Label(parent, image = self.img_label_pass, text = "Password:", bg = '#3c3a3b').place(x = 177,y = 245)
def openMenu(self):
self.myFrame.destroy
self.myFrame2 = Frame()
self.myFrame2.pack()
def read_info(self):
with open("emails.txt") as read_ep:
for line in read_ep:
accounts.append(line.strip().split(", "))
credential = [self.email.get(), self.password.get()]
if credential in accounts:
self.openMenu()
else:
self.ep_notexist = Label(root, text = "Your Email or Password is incorrect, Please try again", font=("open sans", "8"))
self.ep_notexist.place(x = 210, y = 300)
self.ep_notexist.after(4000, self.ep_notexist.destroy)

First destroy all the widgets placed of login page by using
for wid in root.winfo_children():
wid.destroy()
and then pack your new frame. It will work.
(if you don't want to destroy widgets you can also use wid.pack_forget() if you have used pack to place widgets)

You actually do not destroy the frame in the below line:
def openMenu(self):
self.myFrame.destroy # <--- frame is not destroyed actually
It should be:
def openMenu(self):
self.myFrame.destroy()

Related

Cannot create 2 treeview in same window/ Tkinter

when I tried to create 2 treeview inside same window in tkinter , i got an error like this
File "D:\Anaconda Navigator\lib\tkinter\ttk.py", line 1240, in column
return _val_or_dict(self.tk, kw, self._w, "column", column) File
"D:\Anaconda Navigator\lib\tkinter\ttk.py", line 298, in _val_or_dict
res = tk.call(*(args + options)) _tkinter.TclError: Invalid column
index PID.
The reason i got this error is that because I have created another treeview above and the one that i am creating later has different column names and spyder cannot differentiate them.
Thanks for your help.
The error i got is this:
my code is
class swindow:
def __init__(self, window):
#Settings For Supplier Window
self.window = window
self.window.title('TEDARİKÇİLER')
self.window.state('zoomed')
self.window.protocol("WM_DELETE_WINDOW", on_closing)
#Frames for treeview and data entry
self.view = Frame(self.window)
self.viewr =Frame(self.window,bg = 'red')
self.entry= Frame(self.window)
self.rentry = Frame(self.window)
#Labels
self.sheading = Label(self.entry , text = 'Tedarikçi Girişi', font = ('Verdana',17,'bold'),fg = 'blue')
self.sname = Label(self.entry,text = 'Tedarikçi Adı: ', font=('Verdana',12),width =18)
self.sphone = Label(self.entry, text = 'Tedarikçi Tel: ', font=('Verdana',12),width = 18)
self.smail= Label(self.entry, text = 'Tedarikçi Mail Adresi: ', font=('Verdana',12),width=18)
self.sofficer = Label(self.entry, text = 'İlgili Adı: ',font = ('Verdana',12), width =18)
self.headingr = Label(self.rentry,text = 'Tedarik Edilmiş Parça Girişi',font = ('Verdana',17,'bold'),fg = 'red')
self.snamer = Label(self.rentry,text = 'Tedarikçi Adı: ',font = ('Verdana',12), width =18)
self.pnamer = Label(self.rentry,text = 'Parça Adı: ',font = ('Verdana',12), width =18)
self.pbrandr = Label(self.rentry,text = 'Parça Markası: ',font = ('Verdana',12), width =18)
self.quantity = Label(self.rentry,text = 'Parça Adet: ' ,font = ('Verdana',12), width =18)
self.pricer = Label(self.rentry,text = 'Parça Fiyat: ',font = ('Verdana',12), width =18)
#EntryBoxes
self.nameentry = Entry(self.entry , width=20 , font = ('Verdana',12))
self.phoneentry = Entry(self.entry , width=20 , font = ('Verdana',12))
self.mailentry = Entry(self.entry , width=20 , font = ('Verdana',12))
self.officerentry = Entry(self.entry , width=20 , font = ('Verdana',12))
#ComboBoxes and EntryBoxes for Part-Supplier Relationship
self.scombo = ttk.Combobox(self.rentry, width = 20, font = ('Verdana',12))
self.pcombo = ttk.Combobox(self.rentry, width = 20, font = ('Verdana',12))
self.bcombo = ttk.Combobox(self.rentry, width = 20, font = ('Verdana',12))
self.quantityentry = Entry(self.rentry,width = 22,font=('Verdana',12))
self.priceentry = Entry(self.rentry,width = 22,font=('Verdana',12))
#Buttons
self.backbutton = Button(self.window,text='Ana Pencere',font=('Verdana',14), command = self.goback)
self.add = Button(self.entry , text = 'Tedarikçi Ekle',font= ('Verdana',12), bg='chartreuse1',command = self.add_supplier)
self.update = Button(self.entry , text = 'Tedarikçi Güncelle', font= ('Verdana',12),bg='yellow',command = self.update_supplier)
self.delete = Button(self.entry ,text= 'Tedarikçi Sil', font= ('Verdana', 12),bg='red',command = self.delete_supplier)
self.addr = Button(self.rentry,text = 'Tedarikçi-Parça Ekle',font= ('Verdana',12), bg='chartreuse1',command = self.addr)
self.updater = Button(self.rentry,text = 'Tedarikçi-Parça Güncelle', font= ('Verdana',12),bg='yellow',command = self.updater)
#ScrollBar For Treeview
self.scroll = Scrollbar(self.view)
self.yscrollr = Scrollbar(self.viewr)
#Treeview for Supplier Table
self.tree = ttk.Treeview(self.view, yscrollcommand= self.scroll.set, selectmode = 'browse')
self.tree['columns'] = ('SID','SuppName', 'PartName','PartNo','Part Price')
self.headings=['sid','Tedarikçi Adı','Parça Adı','Parça No','Parça Fiyat']
self.tree.column('#0', width= 0, stretch= NO)
for i,j in zip(self.tree['columns'], self.headings):
self.tree.column(i,anchor= CENTER,width= 150, minwidth= 150)
self.tree.heading(i,text = j, anchor = CENTER)
self.tree['displaycolumns'] = ('SuppName', 'PartName','PartNo','Part Price')
#Treeview for Supplier-Part Relation
self.treer = ttk.Treeview(self.viewr , yscrollcommand = self.yscrollr.set, selectmode = 'browse')
self.treer['columns'] = ('SID','PID','Sname','Pname','Pcategory','Squantity','Sdate','Sprice','Pbrand','Ptype')
self.headingsr = ['sid','pid','Tedarikçi Adı','Parça Adı','Parça Kategorisi','Tedarik Edilen Adet','Tedarik Tarihi','Tedarik Fiyatı','Parça Markası','Parça Hammaddesi']
self.treer.column('#0', width = 0, stretch = NO)
for i,j in zip(self.treer['columns'],self.headingsr):
self.tree.column(i,anchor= CENTER,width= 150, minwidth= 150)
self.tree.heading(i,text = j, anchor = CENTER)
self.treer['displaycolumns'] = ('Sname','Pname','Pcategory','Pbrand','Ptype','Squantity','Sdate','Sprice')
#Binding Treeview to ScrollBar
self.tree.bind('<Double-1>', self.selector)
self.scroll.config(command = self.tree.yview)
#Placement of Frames
self.entry.place_configure(x=45,y=30,height= 293, width=475)
self.view.place_configure(width=950,height =256,x=530,y=55)
self.viewr.place_configure(width =950,height=350,x = 530, y=362)
self.rentry.place(x=45 , y = 350, height = 410, width =475)
#Placement of Labels
self.sheading.pack(fill = X)
self.sname.place(x=15 , y=45)
self.sphone.place(x=15 , y=100)
self.smail.place(x=15 , y=155)
self.sofficer.place(x=15 , y=210)
self.headingr.place(x= 49,y=0)
self.snamer.place(x= 5,y=45)
self.pnamer.place(x = 5, y = 100)
self.pbrandr.place(x = 5, y = 155)
self.quantity.place(x = 5, y = 210)
self.pricer.place(x = 5, y = 265)
#Placement of ComboBoxes
self.scombo.place(x =200 , y =45 )
self.pcombo.place(x =200 , y =100 )
self.bcombo.place(x = 200, y = 155)
#Placement of EntryBoxes
self.nameentry.place(x=210, y=45)
self.phoneentry.place(x=210 , y=100)
self.mailentry.place(x=210 , y=155)
self.officerentry.place(x=210, y=210)
self.quantityentry.place(x =200 , y =210 )
self.priceentry.place(x = 200, y = 265)
#Placement of Buttons
self.backbutton.place(x=650,y= 0)
self.add.place(x=15,y=250)
self.update.place(x=150,y=250)
self.delete.place(x=325,y=250)
self.addr.place(x = 0,y = 305 )
self.updater.place(x = 210 ,y =305 )
#Placement of Treeview
self.tree.place(x=0, y=40,height =700, width=933)
self.treer.place(x=0,y=40,height = 700,width=933)
#Placement of ScrollBar
self.scroll.pack(side = RIGHT, fill = Y)
self.window.mainloop()
You used self.tree in the for loop:
for i,j in zip(self.treer['columns'],self.headingsr):
self.tree.column(i,anchor= CENTER,width= 150, minwidth= 150)
self.tree.heading(i,text = j, anchor = CENTER)
But it should be self.treer instead:
for i,j in zip(self.treer['columns'],self.headingsr):
# should use self.treer instead of self.tree
self.treer.column(i,anchor= CENTER,width= 150, minwidth= 150)
self.treer.heading(i,text = j, anchor = CENTER)
Suggest to go through your code and make sure you use the correct instance variable: self.tree or self.treer.

how can i open a second frame without having to open the first frame

how can i open Frame7 without having to open myFrame4 first, when i dont open myFrame4 first i get an Attribute error however when i open myFrame4 first and then go back to open Frame7 it opens, i know this is happening because myFrame4 is being pack_forget() without even being opened and actually being an object but i just dont know how to fix it. (intention is to run def cart_order(self): from the home page but can only do so by running def order_menu(self): first then going back to home page and then run it). hopefully i made sense.
def openMenu(self):
for wid in root.winfo_children():
wid.destroy()
self.myFrame.destroy()
self.myFrame2 = Frame(root)
self.myFrame2.pack(fill = "both", expand = 1)
self.img77 = PhotoImage(file = 'new-dip-project\\goode.png')
self.name77 = Label(self.myFrame2, image = self.img77).pack()
self.img_menu = PhotoImage(file = 'new-dip-project\\menu_button.png')
self.b6 = Button(self.myFrame2,image = self.img_menu, command = self.view_menu, bd = 0)
self.b6.place(x = 246, y = 140)
self.img_order = PhotoImage(file = 'new-dip-project\\order_button.png')
self.b7 = Button(self.myFrame2,image = self.img_order, command = self.order_menu, bd = 0)
self.b7.place(x = 239, y = 228)
self.img_checkout = PhotoImage(file = 'new-dip-project\\checkout.png')
self.b8 = Button(self.myFrame2,image = self.img_checkout, bd = 0, command = self.cart_order)
self.b8.place(x = 250, y = 316)
def cart_order(self):
self.myFrame4.pack_forget()
self.myFrame2.pack_forget()
self.Frame7 = Frame(root)
self.Frame7.pack(fill = "both", expand = 1)
def order_menu(self):
self.myFrame2.destroy()
self.myFrame4 = Frame(root)
self.myFrame4.pack(fill = "both", expand = 1)
self.back_img = PhotoImage(file = 'new-dip-project\\bbutton.png')
self.back_btn2 = Button(self.myFrame4, image = self.back_img, bd = 0, command = self.openMenu)
self.back_btn2.place(x = 50, y = 410)

How do I get tkinter application to update as I change a text file needed?

I have a text file with values that I need to display in a scroll box tkinter. I have been succesful in doing this but there is a problem. When I press submit to add more values to my text file in my program, the scrollbox displaying the contents in the text file does not update with the new values.
Here is a screenshot of the program:
This is my text file:
amazon.com
username#gmail.com
n3*F/X"qse~a`_+
netflix.com
username#outlook.com
avOmCl|Jb?O<
apple.com
username#icloud.com
s=DT8n*Y"y
However when I press submit the text file updates with the values submitted but the scrollbox does not.
Here is my full code:
import string
import random
from tkinter import *
import tkinter.scrolledtext as st
mypasslist = []
with open("password&usernames.txt", "r") as input:
for line in input:
items = line.split()
mypasslist.append([item for item in items[0:]])
def generatePassword():
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(random.choice(characters) for x in range(random.randint(8, 16)))
return password
def writeToFile(input_variable):
with open("password&usernames.txt", "a") as input:
input.writelines(input_variable)
top = Tk()
top.geometry("1920x1080")
def ifSubmit():
global a
a = generatePassword()
label1 = Label(top, text='Your password is: %s' % a, font=("Arial", 11)).place(x = 40, y = 170)
label1 = Label(top, justify='left', text='Your password and username has been saved, you can access them below.').place(x = 40, y = 227)
copy_button = Button(top, text = 'Copy', command=copyText).place(x=40, y=195)
service = service_var.get()
username = username_var.get()
writeToFile('%s\n' % str(service))
writeToFile('%s\n' % str(username))
writeToFile('%s\n' % str(a))
writeToFile('\n')
def copyText():
top.clipboard_clear()
top.clipboard_append(a)
top.update()
# the label for user_name
Service = Label(top, text = "Service").place(x = 40, y = 60)
user_name = Label(top, text = "Username").place(x = 40, y = 100)
submit_button = Button(top, text = "Submit", command=ifSubmit)
submit_button.place(x = 40, y = 130)
service_var = StringVar()
Service_input_area = Entry(top, width = 30, textvariable=service_var)
Service_input_area.place(x = 110, y = 60)
service = service_var.get()
username_var = StringVar()
user_name_input_area = Entry(top, width = 30, textvariable=username_var)
username = username_var.get()
user_name_input_area.place(x = 110, y = 100)
text_area = st.ScrolledText(top, width = 50, height = 10)
text_area.grid(column = 0, pady = 260, padx = 40)
for i in mypasslist:
text_area.insert(INSERT, i)
text_area.insert(INSERT, '\n')
text_area.configure(state ='disabled')
top.mainloop()
So how could I make the program update every time new values have been submitted?
I got it working, I had to do:
def writeToFile(input_variable):
with open("password&usernames.txt", "a") as input:
input.writelines(input_variable)
text_area['state'] = NORMAL
text_area.insert(INSERT, input_variable)
text_area['state'] = DISABLED

Radiobuttons and Checkbuttons not appearing in window

I'm writing a program that draws a rectangle or oval in a top frame depending on whether or not the user selects it via a radiobutton. There is a check button that determines whether the oval is filled as well. Both buttons are on the bottom frame. But for some reason when I run the code, it displays the window, but not the buttons themselves. How do I fix this?
Here's my code:
from tkinter import *
class GeometricFigures:
def __init__(self):
self.window = Tk()
self.window.title("Radiobuttons and Checkbuttons")
self.canvas = Canvas(self.window, width = 300, height = 100, bg = "white")
self.canvas.pack()
def drawButtons(self):
self.bottomframe = Frame(self.window)
self.bottomframe.pack()
self.check = IntVar()
cbtFilled = Checkbutton(self.bottomframe, variable = self.check, value = 0,
text = "Filled", command = self.processCheckbutton).pack(side = LEFT)
self.radio = IntVar()
rbRectangle = Radiobutton(self.bottomframe, variable = self.radio, value = 1,
text = "Rectangle", command = self.processRadiobutton.pack())
rbOval = Radiobutton(self.bottomframe, text = "Oval", variable = self.radio,
value = 2, command = self.processRadiobutton.pack())
cbtFilled.grid(row = 1, column = 2)
rbRectangle.grid(row = 1, column = 3)
rbOval.grid(row = 1, column = 4)
def processCheckbutton(self):
print("The check button is " +
("checked " if self.check.get() == 1 else "unchecked"))
def processRadiobutton(self):
print(("Rectangle" if self.radio.get() == 1 else "Oval")
+ " is selected ")
def drawRect(self):
self.canvas.create_rectangle(30, 10, 270, 60, tags = "rect")
def drawFillOval(self):
self.canvas.create_oval(30, 10, 270, 60, fill = 'blue', tags = "oval")
def drawOval(self):
self.canvas.create_oval(30, 10, 270, 60, tags = "oval")
def main(self):
test = GeometricFigures()
if self.check.get() == 1:
test.drawFillOval()
if self.radio.get() == 1:
test.drawRect()
else:
test.drawOval()
test.drawButtons()
if __name__ == '__main__':
main()
Thanks!

Using Tkinter to program an application need add buttons with same function. How to identify which button I clicked and change the line automatically?

The following things I want is to add multiple different tasks, and there is a task start button which is used to trig a timer.
class Pomodoro_app(Tk):
def add_task(self):
global time
time = StringVar()
time.set("Start")
task_content = askstring(title = 'Add a Task', prompt = "Input a task")
task_label = Label(self, text = task_content, font = ("Arial, 12")).grid(column = 0, row = 3)
task_start_button = Button(self, textvariable = time, command = self.start_working).grid(column = 1, row = 3)
def createWidgets(self):
self.welcome_label = Label(self, text = "Welcome to the Challenge!", font = ("Arial, 12")).grid(column = 0, row = 0, columnspan = 2)
self.add_task_button = Button(self, text = "Add Task", width = 20, command = self.add_task).grid(column = 0 , columnspan = 2)
def __init__(self):
"""GUI Initiation"""
Tk.__init__(self)
self.createWidgets()
"""window Initiation"""
self.resizable(False, False)
x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
self.geometry('250x400+%d+%d' % (x, y))
Using lambda (or inner function), you can pass additional argument to callback.
For example:
class Pomodoro_app(Tk):
def add_task(self):
global time
time = StringVar()
time.set("Start")
task_content = askstring(title = 'Add a Task', prompt = "Input a task")
task_label = Label(self, text = task_content, font = ("Arial, 12")).grid(column = 0, row = self.next_row)
task_start_button = Button(self, textvariable = time, command = lambda: self.start_working(task_content)).grid(column = 1, row = self.next_row)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
self.next_row += 1
def start_working(self, task_name):
print('start working', task_name)
def createWidgets(self):
self.welcome_label = Label(self, text = "Welcome to the Challenge!", font = ("Arial, 12")).grid(column = 0, row = 0, columnspan = 2)
self.add_task_button = Button(self, text = "Add Task", width = 20, command = self.add_task).grid(column = 0 , columnspan = 2)
def __init__(self):
"""GUI Initiation"""
Tk.__init__(self)
self.createWidgets()
"""window Initiation"""
self.resizable(False, False)
x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
self.geometry('250x400+%d+%d' % (x, y))
self.next_row = 3

Categories

Resources