问题描述:

I am currently writing a tkinter GUI app using Python 3. I have several frames in my application which should have the same navigation bar(some button widgets and some Label widgets packed in a LabelFrame widget). I want to write this code in a function and call it instead of writing it to every frame and having to change every frame every time I change something in the navigation bar.

I tried putting all of the widgets in a function and calling it just as I said above but it didn't work because I wrote every frame as a class and when I call the function, it doesn't understand where I want to put the widgets to.I pass self as the first argument for creating the widget to place it in the main frame but when I call it in a function, it can't find what self is.

I am looking for any possible way to "teach" the function self or another way to write the navigation bar only once and make any modifications there.

(I think writing the tkinter GUI by writing frames as class has a specific name but I can't recall it right now)

EDIT: Based on a comment here is a example of what I want to do;

(Example below is written without considering the fact it is not possible to use pack with grid. Any other improvements to the code are welcome.)

from tkinter import ttk

import tkinter as tk

#lots of other imports here, they are not related to the question.

def nav_bar():

navLabelFrame=tk.LabelFrame(self)

button=ttk.Button(navLabelFrame,text="I am a button",

command=lambda:controller.show_frame(Page1))

#Other buttons and labels

#...

class app(tk.Tk):

def __init__(self,*args,**kwargs):

tk.Tk.__init__(self, *args, **kwargs)

tk.Tk.wm_title(self, "Hello World")#TITLE OF THE WINDOW

container = tk.Frame(self)

container.pack(side="top", fill="both", expand = False)

container.grid_rowconfigure(0, weight=1)

container.grid_columnconfigure(0, weight=1)

self.frames = {}

for F in:(Page1,Page2,Page3,

Page4,Page5,Page6):

frame = F(container, self)

self.frames[F] = frame

frame.grid(row=0, column=0, sticky="nsew")

self.show_frame(UserLogin)#SET HOME PAGE

def show_frame(self, cont):#FUNCTION TO SWITCH PAGES

frame = self.frames[cont]

frame.tkraise()

class Page1(tk.Frame):

def __init__(self, parent, controller):

tk.Frame.__init__(self,parent)

Page1.grid(self)

nav_bar()#place the contents of the navbar

#place other stuff here

class Page2(tk.Frame):

def __init__(self, parent, controller):

tk.Frame.__init__(self,parent)

Page1.grid(self)

nav_bar()#place the contents of the navbar

#place other stuff here

class Page3(tk.Frame):

def __init__(self, parent, controller):

tk.Frame.__init__(self,parent)

Page1.grid(self)

nav_bar()#place the contents of the navbar

#place other stuff here

GUI=app()

GUI.mainloop()

相关阅读:
Top