I'm trying to import all the Frames I have inside a folder as a package and then initialize all those frames so I can just raise them on a button press.
This is my folder structure:
+-projectfolder
|--bargraphtutor.py
|-- __init__.py (empty)
|--pages
|--startpage.py
|-- .
|-- .
|--aboutpage.py
|--__init__.py
The __init__.py in the pages folder has the following code to package all the .py files in that folder into pages. That was taken from this question.
from os.path import dirname, basename, isfile, join
import glob
pages = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in pages if isfile(f) and not f.endswith('__init__.py')]
from . import *
And then I get to do import pages as p. The issue is that, each frame is a class in the file and to initialize each frame I have to know the name of each file and class name:
Example: Part of bargraphtutor.py
self.frames = {}
for F in (p.aboutpage.AboutPage, p.startpage.StartPage): # This is where I'd like to make as
page_name = F.__name__ # automated as possible.
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
Example: startpage.py:
import tkinter as tk # python 3
from tkinter import ttk
from tkinter.ttk import Label, Button
from tkinter import font
class StartPage(tk.Frame): # Each Frame is defined via a class
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
titleLabel= ttk.Label(self, text='This is the Startpage')
titleLabel.pack()
So how can I import the package and then iterate over all the Frames in bargraphtutor.py but without knowing all the class names? I got as far as using p.__all__ which returns the names of all the files in the package but I don't know how to move forward from there.
Edit: If I named the file the same as the class, would I run into problems with namespaces?