how to remove a circular dependency in tkinter gui - python-3.x

I'm in the very early stages of making a GUI. Right now I have the log in view(LogInWind class) and the sign up view (SignUpWind class). Everything was fine when I only had one view but now I have a circular dependency with these two objects. This happens with the buttons' command since in the log in view there is a button that takes you to the sign up view and vise versa. I think I could just make a pop up window for the sign up view. Yet I think the way I'm switching windows is a bad practice an may bring bigger issues later on.
I'm project structure is the following.
the services package will do the connection between the gui and the database. At the moment it does nothing.
I'm happy to get feedback for everything. If further explanation is needed I'm happy to do so.
root.py
import tkinter as tk
from .log_in_window import LogInWind as LIWind
from .sign_up_window import SignUpWind as SuWind
from services.messenger import Messenger
class Root(tk.Tk):
def __init__(self, *args,**kwargs):
super().__init__(*args,**kwargs)
# General variables.
self.frames = {}
self.width_window
self.height_window
self.container = tk.Frame(self,relief="groove")
# General app configurations.
self.title("SECOM")
self.iconbitmap("C:/Users/joshu/Documents/VSC/python/secom/icons/icon.ico")
self.configure(bg="#E0E0E0")
# Container setup.
self.container.pack(side="top", fill="both", expand=True)
self.container.grid_rowconfigure(0, weight=1)
self.container.grid_columnconfigure(0, weight=1)
def createFrame(self, page_name):
"""
INPUT: view object.
OUTPUT: None
Description: creates frame for the view `page_name`.
"""
# Setup `newFrame.`
newFrame = page_name(parent=self.container, controller=self)
newFrame.configure(bg="#E0E0E0")
newFrame.grid(row=0, column=0, sticky=tk.NSEW)
# Add `newFrame` to catalog of frames.
self.__frames[page_name] = newFrame
def showFrame(self, page_name):
"""
INPUT: view object.
OUTPUT: None.
Calls the view `page_name` up front for display.
"""
try:
# Bings requested view to the front.
self.frames[page_name].tkraise()
except KeyError:
# Creates view and displays it.
self.createFrame(page_name)
self.frames[page_name].tkraise()
def setLocation(self):
"""
INPUT: None
OUTPUT: None
Description: Sets window in the middle of the screen.
"""
self.widthWindow = 400
self.heightWindow = 225
widthScreen = self.winfo_screenwidth()
hightScreen = self.winfo_screenheight()
x = (widthScreen / 2) - (self.widthWindow / 2)
y = (hightScreen / 2) - (self.heightWindow / 2)
self.geometry("%dx%d+%d+%d" % (self.widthWindow, self.heightWindow, x, y))
log_in_window.py
import tkinter as tk
import tkinter.font as tkf
from .sign_up_window import SignUpWind as SUWind # <-- circular dependency
class LogInWind(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent, controller)
# Creation of labels.
self.titleLbl = tk.Label(self,
text="Iniciar Secion",
font=tkf.Font(family="Helvetica", size=15, weight="bold"),
bg="#E0E0E0")
self.userLbl = tk.Label(self,
text="Usuario:",
font=tkf.Font(family="Helvetica", size=10, weight="bold"),
bg="#E0E0E0")
self.pswdLbl = tk.Label(self,
text="Contraseña:",
font=tkf.Font(family="Helvetica", size=10, weight="bold"),
bg="#E0E0E0")
# Creation of entries.
self.userEty = tk.Entry(self)
self.pswdEty = tk.Entry(self, show="*")
# Creation of buttons.
self.logInBtn = tk.Button(self,
width=15,
text="Iniciar Sesion",
font=tkf.Font(family="Helvetica", size=10, weight="bold"),
bg="#0080FF",
################################### ADD COMMAND
fg="#fff")
self.signUpBtn = tk.Button(self,
width=15,
text="Crear cuenta",
font=tkf.Font(family="Helvetica", size=10, weight="bold"),
bg="#0080FF",
command=lambda: controller.showFrame(SUWind), # <---- use object HERE.
fg="#fff")
# Places labels.
self.titleLbl.grid(row=0,
column=0,
padx=400 / 2 - 60,
pady=10,sticky=tk.SW)
self.userLbl.grid(row=1,
column=0,
padx=parent.width_window / 2 - 60,
sticky=tk.SW)
self.pswdLbl.grid(row=3,
column=0,
padx=parent.width_window / 2 - 60,
sticky=tk.W)
# Places entries (string inputs).
self.userEty.grid(row=2,
column=0,
padx=parent.width_window / 2 - 60,
pady=5)
self.pswdEty.grid(row=4,
column=0,
padx=parent.width_window / 2 - 60,
pady=5)
# # Places buttons
self.logInBtn.grid(row=5,column=0, sticky=tk.N)
self.signUpBtn.grid(row=6, column=0, sticky=tk.S, pady=10)
sing_up_window.py
import tkinter as tk
import tkinter.font as tkf
from .log_in_window import LogInWind as LIWind # <-- circular dependency
class SignUpWind(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent, controller)
# Setup imge for back button.
self.img = tk.PhotoImage(file="C:/Users/joshu/Documents/VSC/python/secom/icons/return.png")
self.img = self.img.subsample(4,4)
# Create label.
self.titleLbl = tk.Label(self,
text="Crear cuenta nueva",
font=tkf.Font(family="Helvetica", size=15, weight="bold"),
bg="#E0E0E0")
self.userLbl = tk.Label(self,
text="Usuario:",
font=tkf.Font(family="Helvetica", size=10, weight="bold"),
bg="#E0E0E0")
self.pswdLbl = tk.Label(self,
text="Contraseña:",
font=tkf.Font(family="Helvetica", size=10, weight="bold"),
bg="#E0E0E0")
self.pswdConfirmLbl = tk.Label(self,
text="Cormirma Contraseña:",
font=tkf.Font(family="Helvetica", size=10, weight="bold"),
bg="#E0E0E0")
# Creation of entries.
self.userEty = tk.Entry(self)
self.pswdEty = tk.Entry(self, show="*")
self.pswdConfirmEty = tk.Entry(self, show="*")
# Creation of button.
self.backBtn = tk.Button(self,
image=self.img,
command=lambda: controller.showFrame(LIWind)) <----- use object HERE.
self.CreateBtn = tk.Button(self,
width=8,
text="Crear",
font=tkf.Font(family="Helvetica", size=10, weight="bold"),
bg="#0080FF",
############################ ADD COMAND
fg="#fff")
# Places labels.
self.titleLbl.grid(row=0, column=0, padx=400 / 2 - 90, sticky=tk.SW)
self.userLbl.grid(row=1, column=0, padx=parent.width_window / 2 - 60, sticky=tk.W)
self.pswdLbl.grid(row=3, column=0, padx=parent.width_window / 2 - 60, sticky=tk.W)
self.pswdConfirmLbl.grid(row=5, column=0, padx=parent.width_window / 2 - 60, sticky=tk.W)
# Places entries (string inputs).
self.userEty.grid(row=2, column=0, padx=parent.width_window / 2 - 60, pady=5, sticky=tk.W)
self.pswdEty.grid(row=4, column=0, padx=parent.width_window / 2 - 60, pady=5, sticky=tk.W)
self.pswdConfirmEty.grid(row=6, column=0, padx=parent.width_window / 2 - 60, pady=5, sticky=tk.W)
# Places buttons
self.backBtn.grid(row=0, column=0,sticky=tk.W)
self.CreateBtn.grid(row=7, column=0, padx=100,sticky=tk.N)
main.py
from views.root import Root
from views.log_in_window import LogInWind as LIWind
if __name__ == '__main__':
root = Root()
root.showFrame(LIWind)
root.mainloop()

If you design your code so that you pass in the page name as a string rather than as a class then you won't have this problem.
For example, in root.py you can start with something like this:
pages = {
"log in": LIWind,
"sign up": SuWind,
}
Next, in createFrame you would do something like this:
def createFrame(self, page_name):
...
cls = pages[page_name]
newFrame = cls(parent=self.container, controller=self)
...
self.__frames[page_name] = newFrame
Then, anywhere you need the window you can pass in the page name, such as:
self.backBtn = tk.Button(..., command=lambda: controller.showFrame("log in"))

Related

How to create a class to close GUI and exit Python

I have been trying to find a way to do this for a while to no avail. I would like to create a class to completely close my GUI in tkinter and I'm not having much luck. I've tried sys.exit and .destroy() a few different ways. I can manage to do what I want without using classes but I'm rather new to OOP. Here is my code:
import sys as system
import tkinter as tk
from tkinter import ttk
class headerFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
#setup the grid layout manager
self.columnconfigure(0, weight=1)
self._create_widgets()
def _create_widgets(self):
#header bar
canvas = tk.Canvas(self, bg='#0066cc', highlightthickness=0, height=45, width=600)
canvas.grid(column=0, row=0, sticky=tk.W)
label = ttk.Label(self, text='Production Assistant', background='#0066cc', foreground='White', font=('calibri', 18, 'bold'))
label.grid(row=0, column=0)
class loginFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
#setup the grid layout manager
self.columnconfigure(0, weight =1)
self.columnconfigure(0, weight=3)
self._create_widgets()
def _create_widgets(self):
#username
ttk.Label(self, text='Username: ', justify='right').grid(row=0, column=0, sticky=tk.E)
username = ttk.Entry(self, width=33)
username.focus()
username.grid(row=0, column=1, sticky=tk.W)
#password
ttk.Label(self, text='Password: ', justify='right').grid(row=1, column=0, sticky=tk.E)
password = ttk.Entry(self, width=33, show='*')
password.grid(row=1, column=1, sticky=tk.W)
#add padding
for widget in self.winfo_children():
widget.grid(padx=0, pady=5)
class loginButtonFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
#setup the grid layout manager
self.columnconfigure(0, minsize=62)
self._create_widgets()
def _create_widgets(self):
#buttons
ttk.Button(self, text='Login', width=15).grid(row=0, column=1)
ttk.Button(self, text='Forgot Login', width=15).grid(row=0, column=2)
ttk.Button(self, text='Request Access', width=15).grid(row=1, column=1)
ttk.Button(self, text='Exit', width=15, command=exitButton).grid(row=1, column=2)
#add padding to buttons
for widget in self.winfo_children():
widget.grid(padx=3, pady=3)
class exitButton():
def exit():
#code to close gui and program
#create the main application
class mainLogin(tk.Tk):
def __init__(self):
super().__init__()
self.title('Login')
self.geometry('325x175')
self.resizable(0, 0)
self.configure(background='#444444')
#windows only (remove the minimize/maximize buttons)
self.attributes('-toolwindow', True)
#TCL to center the screen
self.eval('tk::PlaceWindow . center')
#layout on the root window
self.columnconfigure(0, weight=1)
self._create_Styles()
self._create_widgets()
def _create_Styles(self):
#create styles
s = ttk.Style()
s.configure('TFrame', background='#444444')
s.configure('TLabel', background='#444444', foreground='white')
s.configure('TButton', background='#878683', foreground='black')
def _create_widgets(self):
#create the header frame
_header_frame = headerFrame(self)
_header_frame.grid(column=0, row=0)
#create the login frame
_login_frame = loginFrame(self)
_login_frame.grid(column=0, row=1, sticky=tk.N)
#create the button frame
_login_button_frame = loginButtonFrame(self)
_login_button_frame.grid(column=0, row=2)
if __name__ == '__main__':
app = mainLogin()
app.mainloop()
class exitButton() is what I would like to call from multiple different pages in the application to close everything.
Any help is appreciated, I'm trying to learn as I build so if you have any suggested reading based around Python that would help with this I would appreciate it!

Is it possible to grab input from the topview tkinter window and retrieve saved entry field value from within master tk window

The program is made up of classes and I am trying to use a tkinter topview from within a function so that when it's called it is able to retrieve the entryfield value to the master class
from tkinter import
from PIL import Image, ImageTk
Below is the driver code handling the transitioning from one class to another
class SeaofBTCapp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (
WelcomePage, Register_new_user): # ,PageThree,PageFour):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(WelcomePage)
# def show_frame(self, cont):
# frame = self.frames[cont]
# frame.tkraise()
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
frame.update()
frame.event_generate("<<show_frame>>")
def get_page(self, cont):
for page in self.frames.values():
if str(page.__class__.__name__) == cont:
return page
return None
class Register_new_user(object):
pass
Below is the entry point of the program and is the first page to be displayed
class WelcomePage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
# self.bind("<<show_frame>>", self.main_prog)
def resize_image(event):
global photo
new_width = event.width
new_height = event.height
image = copy_of_image.resize((new_width, new_height))
photo = ImageTk.PhotoImage(image)
label.config(image=photo)
label.image = photo # avoid garbage collection
def pin_input():
top = Toplevel()
top.geometry("180x100")
top.title("toplevel")
l2 = Label(top, text="This is toplevel window")
global entry_1
global password
password = StringVar
entry_1 = None
def cleartxtfield():
global password
new = "3"
password.set(new)
# ############# Function to parse for only numerical input
def validate(input):
if input.isdigit():
return True
elif input == "":
return True
else:
return False
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
entry_1 = Entry(top, textvariable=password, width=64, show='*')
entry_1.place(x=200, y=100)
entry_1.focus()
reg = top.register(validate)
entry_1.config(validate="key", validatecommand=(reg, '%P'))
def getcreds():
# check if four digit entered and is not empty
global passwd
passwd = password.get()
print(f"The Credentials are {passwd}")
def funcbackspace():
length = len(entry_1.get())
entry_1.delete(length - 1, 'end')
def killwindow():
# when the user quits it should clear all the data input fields filled in in the previous steps. and should display information that it is about to quit in a few seconds
command = top.destroy()
# Label(top,text="Goodbye\n (Closing in 2 seconds)")
top.after(2000, top.quit())
cancel = Button(top, width=8, height=3, text="Cancel", bg="red", fg="black", command=killwindow)
cancel.place(x=220, y=150)
backspace = Button(top, width=8, height=3, text="Backspace", bg="red", fg="black", command=funcbackspace)
backspace.place(x=500, y=150)
# ----number Buttons------
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
btn_numbers = []
for i in range(10):
btn_numbers.append(
Button(top, width=8, height=3, text=str(i), bd=6, command=lambda x=i: enternumber(x)))
btn_text = 1
for i in range(0, 3):
for j in range(0, 3):
btn_numbers[btn_text].place(x=220 + j * 140, y=250 + i * 100)
btn_text += 1
btn_zero = Button(top, width=15, height=2, text='0', bd=5, command=lambda x=0: enternumber(x))
btn_zero.place(x=330, y=550)
clear = Button(top, text="Clear", bg="green", fg="white", width=8, height=3, command=cleartxtfield)
clear.place(x=220, y=550)
okbtn = Button(top, text="Enter", bg="green", fg="black", width=8, height=3, command=getcreds)
okbtn.place(x=500, y=550)
val = getcreds()
print("The value to be returned is %s" % val)
return val
password = pin_input()
print("Gotten password is %s" % password)
copy_of_image = Image.open("image.png")
photoimage = ImageTk.PhotoImage(copy_of_image)
label = Label(self, image=photoimage)
label.place(x=0, y=0, relwidth=1, relheight=1)
label.bind('<Configure>', resize_image)
top_left_frame = Frame(self, relief='groove', borderwidth=2)
top_left_frame.place(relx=1, rely=0.1, anchor=NE)
center_frame = Frame(self, relief='raised', borderwidth=2)
center_frame.place(relx=0.5, rely=0.75, anchor=CENTER)
Button(top_left_frame, text='REGISTER', bg='grey', width=14, height=1,
command=lambda: controller.show_frame(Register_new_user)).pack()
Button(center_frame, text='ENTER', fg='white', bg='green', width=13, height=2,
command=lambda: controller.show_frame(Register_new_user)).pack()
if __name__ == '__main__':
app = SeaofBTCapp()
app.title("Password return on topview window")
width = 1000
height = 700
screenwidth = app.winfo_screenwidth()
screenheight = app.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
app.geometry(alignstr)
# app.resizable(width=False, height=False)
app.resizable(width=True, height=True)
app.mainloop()
If I understand this correctly you want to enter a password in a dialog and then get the password from the dialog when you close it.
Have a look at Dialog Windows at effbot for a discussion about creating dialog windows.
Here is an example of how you can implement a simple dialog:
from tkinter import *
from tkinter import simpledialog
class MyDialog(simpledialog.Dialog):
def body(self, master):
'''create dialog body.
return widget that should have initial focus.
This method should be overridden, and is called
by the __init__ method.'''
Label(master, text='Value:').grid(row=0)
self.e1 = Entry(master)
self.e1.grid(row=0, column=1)
return self.e1 # initial focus
def apply(self):
'''process the data
This method is called automatically to process the data, *after*
the dialog is destroyed. By default, it does nothing.'''
value = self.e1.get()
self.result = value
def validate(self):
'''validate the data
This method is called automatically to validate the data before the
dialog is destroyed. By default, it always validates OK.'''
return 1 # override
def buttonbox(self):
'''add standard button box.
override if you do not want the standard buttons
'''
box = Frame(self)
w = Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side='left', padx=5, pady=5)
w = Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side='left', padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
if __name__ == '__main__':
root = Tk()
root.geometry('200x100+800+50')
def do():
d = MyDialog(root)
print(d.result)
b = Button(root, text='Go!', width=10, command=do)
b.pack(expand=True)
Did that answer your question?

tkinter error calling function through entries in listbox

Recently, I tried to make a full application window with a side panel menu with separate frames running some functions and submitting forms in the canvas frame.
But I found that every time I click on any entry in listbox it runs the function or method without clearing the existing one .
I tried destroy() and forget() didn't work for me (maybe I didn't know exactly how to use it?!, and the destroy() function prevent using the function again till I close the whole application and run it again!) this is a photo of my problem
this is my code :
import tkinter as tk
from tkinter import ttk
class MainWindow() :
def __init__(self,root):
# menu left
self.menu_upper_frame = tk.Frame(root, bg="#dfdfdf")
self.menu_title_label = tk.Label(self.menu_upper_frame, text="menu title", bg="#dfdfdf")
self.menu_title_label.pack()
self.menu_left_container = tk.Frame(root, width=150, bg="#ababab")
self.menu_left_upper = tk.Frame(self.menu_left_container, width=150, height=150, bg="red")
self.menu_left_upper.pack(side="top", fill="both", expand=True)
# create a listbox of items
self.Lb1 = tk.Listbox(self.menu_left_upper,bg ="red", borderwidth=0, highlightthickness=0 )
self.Lb1.insert(1, "Python")
self.Lb1.insert(2, "Perl")
self.Lb1.insert(3, "C")
self.Lb1.insert(4, "PHP")
self.Lb1.insert(5, "JSP")
self.Lb1.insert(6, "Ruby")
self.Lb1.bind("<<ListboxSelect>>", self.OnClick ) #return selected item
self.Lb1.pack(fill="both", expand=True, pady=50 )
# right area
self.inner_title_frame = tk.Frame(root, bg="#dfdfdf")
self.inner_title_label = tk.Label(self.inner_title_frame, text="inner title", bg="#dfdfdf")
self.inner_title_label.pack()
self.canvas_area = tk.Canvas(root, width=500, height=400, background="#ffffff")
self.canvas_area.grid(row=1, column=1)
# status bar
self.status_frame = tk.Frame(root)
self.status = tk.Label(self.status_frame, text="this is the status bar")
self.status.pack(fill="both", expand=True)
self.menu_upper_frame.grid(row=0, column=0, rowspan=2, sticky="nsew")
self.menu_left_container.grid(row=1, column=0, rowspan=2, sticky="nsew")
self.inner_title_frame.grid(row=0, column=1, sticky="ew")
self.canvas_area.grid(row=1, column=1, sticky="nsew")
self.status_frame.grid(row=2, column=0, columnspan=2, sticky="ew")
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(1, weight=1)
def OnClick(self,event):
widget = event.widget
selection = widget.curselection()
value = widget.get(selection)
if value == 'Python':
self.tabtop()
def tabtop(self):
self.tabControl = ttk.Notebook(self.canvas_area, width=400) # Create Tab Control
self.tab1 = ttk.Frame(self.tabControl) # Create a tab
self.tab2 = ttk.Frame(self.tabControl)
self.tab3 = ttk.Frame(self.tabControl)
self.tab4 = ttk.Frame(self.tabControl)
self.tab5 = ttk.Frame(self.tabControl)
self.tabControl.add(self.tab1, text='Login data' ) # Add the tab
self.tabControl.add(self.tab2, text='Permission')
self.tabControl.add(self.tab3, text='Roles')
self.tabControl.add(self.tab4, text='Personal data')
self.tabControl.add(self.tab5, text='Business data')
self.tabControl.pack(expand=1, fill="both") # Pack to make visible
self.l2 = tk.Label(self.tab2, text="label 2").pack()
self.l3 = tk.Label(self.tab3, text="label 3").pack()
root = tk.Tk()
root.title("Control Panel")
root.style = ttk.Style()
root.style.theme_use("clam")
user = MainWindow(root)
root.mainloop()
If what you're really asking is how to replace an existing notebook with a new notebook, all you need to do is call destroy() on the old notebook before creating the new one.
First, define self.tabControl to None somewhere in MainWindow.__init__. Then, in tabtop you can delete the old notebook before creating the new one:
def tabtop(self):
if self.tabControl is not None:
self.tabControl.destroy()
...

Tkinter listbox entry pagination

Recently, I tried to find a way to paginate through listbox entries that runs functions that opens frames with forms, tabs or else, but I didn't find it.
Clearly, I wanna create a control panel application which has a side panel which can switch between pages/frames that hold widgets that user will interact with.
this is the code which I wrote to try to achieve this manner:
import tkinter as tk
from tkinter import ttk
class MainWindow() :
def __init__(self,root):
# menu left
self.menu_upper_frame = tk.Frame(root, bg="#dfdfdf")
self.menu_title_label = tk.Label(self.menu_upper_frame, text="menu title", bg="#dfdfdf")
self.menu_title_label.pack()
self.menu_left_container = tk.Frame(root, width=150, bg="#ababab")
self.menu_left_upper = tk.Frame(self.menu_left_container, width=150, height=150, bg="red")
self.menu_left_upper.pack(side="top", fill="both", expand=True)
# create a listbox of items
self.Lb1 = tk.Listbox(self.menu_left_upper,bg ="red", borderwidth=0, highlightthickness=0 )
self.Lb1.insert(1, "Python")
self.Lb1.insert(2, "Perl")
self.Lb1.insert(3, "C")
self.Lb1.insert(4, "PHP")
self.Lb1.insert(5, "JSP")
self.Lb1.insert(6, "Ruby")
self.Lb1.bind("<<ListboxSelect>>", self.OnClick ) #return selected item
self.Lb1.pack(fill="both", expand=True, pady=50 )
# right area
self.inner_title_frame = tk.Frame(root, bg="#dfdfdf")
self.inner_title_label = tk.Label(self.inner_title_frame, text="inner title", bg="#dfdfdf")
self.inner_title_label.pack()
self.canvas_area = tk.Canvas(root, width=500, height=400, background="#ffffff")
self.canvas_area.grid(row=1, column=1)
# status bar
self.status_frame = tk.Frame(root)
self.status = tk.Label(self.status_frame, text="this is the status bar")
self.status.pack(fill="both", expand=True)
self.menu_upper_frame.grid(row=0, column=0, rowspan=2, sticky="nsew")
self.menu_left_container.grid(row=1, column=0, rowspan=2, sticky="nsew")
self.inner_title_frame.grid(row=0, column=1, sticky="ew")
self.canvas_area.grid(row=1, column=1, sticky="nsew")
self.status_frame.grid(row=2, column=0, columnspan=2, sticky="ew")
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(1, weight=1)
def OnClick(self,event):
widget = event.widget
selection = widget.curselection()
value = widget.get(selection)
# print ("selection: ",selection, ": '%s'"% value)
if value == 'Python':
self.tabtop()
def tabtop(self):
self.tabControl = ttk.Notebook(self.canvas_area, width=400)
self.tab1 = ttk.Frame(self.tabControl)
self.tab2 = ttk.Frame(self.tabControl)
self.tab3 = ttk.Frame(self.tabControl)
self.tab4 = ttk.Frame(self.tabControl)
self.tab5 = ttk.Frame(self.tabControl)
self.tabControl.add(self.tab1, text='Login data' )
self.tabControl.add(self.tab2, text='Permission')
self.tabControl.add(self.tab3, text='Roles')
self.tabControl.add(self.tab4, text='Personal data')
self.tabControl.add(self.tab5, text='Business data')
self.tabControl.pack(expand=1, fill="both")
self.l2 = tk.Label(self.tab2, text="label 2").pack()
self.l3 = tk.Label(self.tab3, text="label 3").pack()
root = tk.Tk()
root.title("Control Panel")
root.style = ttk.Style()
root.style.theme_use("clam")
user = MainWindow(root)
root.mainloop()
If you have an idea to achieve the same manner with a different algorithm please suggest!

Python frames tkinter

Im having troubles with tkinter frames
The folowing code must display labels at left side and there should be more space the button and the label , there is something wrong with my column/row setup. What am i doing wrong?
What is the correct way for a program to display information? 1 global frame with several smaller frames in it? With tkinter when using a menu with page 1 page 2 and page 3 ,
page 1 has 3 input fields , child of FramePage1 , page 2 has 2 buttons child of FramePage2, page 3 has one big text field child of FramePage3. Is it the correct way to use for changing the pages
#menu tab1 -> command #calls function page1
def page1():
self.Framepage2.grid_forget()
self.Framepage1.grid()
#content of the page
or are there other ways to use different layout style pages?
import tkinter
import tkinter as tk
class sjabloon():
def __init__(self):
#make window
self.win = tk.Tk()
self.win.geometry("600x600+10+10")
#make top frame
self.frame_header = tk.Frame(self.win, background='black', width=600, height=50)
self.frame_header.grid(column=0, row=0 , columnspan= 10)
#make body frame
self.frame_body = tk.Frame(self.win, width=600, height=400)
self.frame_body.grid(column=0, row=1 , columnspan= 10)
#button1 select
tk.Label(self.frame_body, text="Select:").grid(column=0, row=2, stick='W')
self.button1 = tk.Button(self.frame_body, text="Select")
self.button1.grid(row=2, column=5, stick='W')
#button1 select
tk.Label(self.frame_body, text="Select:").grid(column=0, row=3, stick='W')
self.button2 = tk.Button(self.frame_body, text="Select")
self.button2.grid(row=4, column=5, stick='W')
#button submit
self.submit = tk.Button(self.frame_body, text="Start")
self.submit.grid(row=10, column=9, stick='W')
#make body footer
self.frame_footer = tk.Frame(self.win, background='yellow', width=600, height=50)
self.frame_footer.grid(column=0, row=3 , columnspan= 10)
if __name__ == "__main__":
sjabloon = sjabloon()
I suggest you to follow this tkinter GUI tutorial, he makes a pretty big app and even if it's not what you exactly looking for, it will help you.
In the part 4, he make a multiple frame architecture in the tkinter GUI.
For switching "pages", i know 2 choices (there's more i think but i don't know them, i'm still a beginner). You can create all the frames inside a window/Frame and raise to the front the one you want (that's in the tutorial part 4) or you can destroy the widgets "Page 1" inside the body frame and create the widgets "Page 2" inside it (obviously in methods/functions to let you switch between the pages).
For your first problem, i'm not sure if i understand your problem, you want more space around your button widget ? if that's what you want, you can use the option padx=(leftPadx,RightPadx) like that :
self.button1.grid(row=2, column=5, stick='W', padx=(50,0))
EDIT : i made a little architecture for you (from what i learn in that tutorial)
Basically, you create all the "Page", you add them in the bodyFrame and you raise to the front the one you want. To achieve that, for each "Page", you create a class that inherits tk.Frame and you add an instance of that class in the mainWindow
import tkinter as tk
from tkinter import ttk
LARGE_FONT = ("Verdana 12")
NORM_FONT = "Verdana 10"
SMALL_FONT = ("Verdana 8")
ERROR_404 = "Error 404 : Page not found !"
class sjabloon(tk.Tk):
def __init__(self, *args, **kwargs):
#make window
tk.Tk.__init__(self, *args, **kwargs)
self.geometry("600x600+10+10")
#make top frame
self.frame_header = tk.Frame(self, background='black', width=600, height=50)
self.frame_header.grid(column=0, row=0 , columnspan= 10)
#make body frame
container = tk.Frame(self, width=600, height=400)
container.grid(column=0, row=1 , columnspan= 10)
#list of Pages
self.frames = {}
#everytime you create a "Page", you add it there
for F in (StartPage, HomePage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=1, column = 0, sticky="nsew", columnspan= 10)
self.show_page("StartPage")
#make body footer
self.frame_footer = tk.Frame(self, background='yellow', width=600, height=50)
self.frame_footer.grid(column=0, row=3 , columnspan= 10)
def show_page(self, page_name):
"""
let us use the NAME of the class to display(the function show_frame
use directly the class).
when we use the classe name, we can put our classes in defferent
files
"""
for F in self.frames:
if F.__name__ == page_name:
self.show_frame(F)
return
print(ERROR_404)
def show_frame(self, cont):
"""raise to the front the frame we want
:param cont: the frame
"""
frame = self.frames[cont]
frame.tkraise()
class HomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#button1 select
tk.Label(self, text="Select:").grid(column=0, row=2, stick='W')
self.button1 = tk.Button(self, text="Select")
self.button1.grid(row=2, column=5, stick='W', padx=(50,0))
#button1 select
tk.Label(self, text="Select:").grid(column=0, row=3, stick='W')
self.button2 = tk.Button(self, text="Select")
self.button2.grid(row=4, column=5, stick='W', padx=(50,0))
#button submit
self.submit = tk.Button(self, text="Start")
self.submit.grid(row=10, column=9, stick='W')
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="""ALPHA application.
use at your own risk. There is no promise
of warranty""", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = ttk.Button(self, text="Agree",
command=lambda: controller.show_page("HomePage"))
button1.pack()
button2 = ttk.Button(self, text="Disagree",
command=controller.destroy)
button2.pack()
if __name__ == "__main__":
sjabloon = sjabloon()
sjabloon.mainloop()

Resources