我试图动态地将子帧添加到主Frame小部件。子帧是其中带有按钮的列,我为子帧创建了一个单独的类,以便将子帧作为列表中的对象,以便稍后我可以更改它们。实际上,额外列的数量也取决于用户输入。
我首先使用网格管理器将小部件添加到主框架,稍后我使用网格向子框架添加按钮。我希望网格能够在不同的帧中使用时实现,但看起来子帧类中的网格调用会将小部件直接放在主框架内而不是在子框架内。
代码:
import tkinter as tk
extra_columns = 1
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.grid(sticky="nsew")
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (MainFrame,):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("MainFrame")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class MainFrame(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.subframes = []
self.init_main()
self.init_subframes()
def init_main(self):
self.title = tk.Label(text='Title')
self.title.grid(row=0, column = 2)
for i in range(1, 3):
b = tk.Button(text=str(i))
b.grid(row=i, column=0)
c = tk.Button(text=str(i+10))
c.grid(row=i, column=2+extra_columns+1)
def init_subframes(self):
for i in range(1, extra_columns+1):
m = SubFrame(self)
self.subframes.append(m)
m.grid(row=1, column=2+i, rowspan=5)
class SubFrame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
for i in range(1, 6):
b = tk.Button(text="extra"+str(i), command=lambda: print("button \
pressed"))
b.grid(row=i, column=0)
root = App()
root.mainloop()
记录:我显示主框架(在App类中)的方式取自pythonprogramming.net上的教程,也用于我的实际代码。
谢谢!
答案 0 :(得分:2)
如Bryan's comment中所述,在创建窗口小部件(框架,按钮,标签等)对象时,除非显式地将框架对象作为父对象传递,否则假定根窗口为父窗口。
如果您想以帧为单位管理几何图形,则需要将窗口小部件的父窗口指定为该帧。
检查以下代码:
import tkinter as tk
#creates a window object named root, this object is the default parent for ever widget object
root = tk.Tk()
#creates a frame that is a child of object named 'root'
mainFrame = tk.Frame(master=root)
#creates a frame that is a child of 'mainFrame'
subFrame_mainFrame = tk.Frame(mainFrame)
#creates a button that is a child of 'subFrame'
button_subFrame_mainFrame_root = tk.Button(master=subFrame)
#creates a button that is a child of default, which is 'root' in this case
button_root = tk.Button()
#creates a button that is a child of mainFrame
button_mainFrame = tk.Button(mainFrame)
你可以管理框架内容的几何形状,与主窗口或其他任何内容无关,只要您正确地将框架的子项分配给它作为父级。
Here是一个关于模块化管理几何体的示例。