Home > Net >  tkinter: how to inherit widgets from another .py file
tkinter: how to inherit widgets from another .py file

Time:01-03

I have 3 rather large tkinter files, each working perfectly, but would like to have them placed on one screen: how to use pages I have learned recently from this forum (TY). Now, I would like to have most of the coding for the separate pages done in separate .py files. However, especially in case of widgets, I can not figure out how to use the frame names in the separate .py file. I do realize, as I tried it, that the function for the label creation is

way shortened example:

Main.py

from functions import *

root = tk.Tk()
root.title("Kombucha Program")
root.geometry("1400x800")
root.minsize(width=900, height=600)
    #root.maxsize(width=1400, height = 900)
root.grid_rowconfigure(3, weight=1)
root.grid_columnconfigure(2, weight=1)
root.configure( bg = '#000080' )

theFrame = tk.Frame(root, width=1200, height = 630, bg = 'yellow')       #0059b3')
theFrame.grid(column=0,row=1, sticky = N, in_ = root)

getlabels()

mainloop()

functions.py

def getLabels():
    exitButton = tk.Button(theFrame, text="Quit the Program",  width = 12, command=root.destroy)
    exitButton.grid(row = 0, column = 0)

CodePudding user response:

As far as your code in question is concerned, you will have to pass the frame as an argument to the function.

def getLabels(theFrame):
    root = theFrame.master # Get the parent window from the frame itself
    exitButton = tk.Button(theFrame, text="Quit the Program",  width = 12, command=root.destroy)
    exitButton.grid(row = 0, column = 0)

...and while calling it, pass the required frame:

getlabels(theFrame)

Also notice that I extracted root from the frame as root it is not within the scope of functions.py. But honestly you can make the structure of your project more better if you use classes and make each frame as a class.

  • Related