我在 tkinter 中将“页面”堆叠在一起时遇到问题。
我有一个主Frame
包含两个子帧,两个子帧都包含不同的信息。第一个子帧包含Listbox
和几个按钮,位于主框架的左侧。第二个框架应该包含不同的“页面”(现在有两个)并让它们填满整个框架。
我的问题是两个“页面”并排显示,而不是彼此重叠。
import tkinter as tk
class Settings(tk.Tk):
def __init__(self, master=None):
tk.Tk.__init__(self, master)
self.focus_force()
self.grab_set()
# set focus to settings window
# Main window title
self.title("Settings")
# set up grid containers
container_main = tk.Frame(self, width=500, height=700)
container_main.pack(side='top', fill='both', expand=True)
container_main.grid_rowconfigure(0, weight=1)
container_main.grid_columnconfigure(0, weight=1)
container_listbox = tk.Frame(container_main, bg='blue', width=200, height=700)
container_listbox.pack(side='left', fill='both', expand=True)
container_listbox.grid_rowconfigure(0, weight=1)
container_listbox.grid_columnconfigure(0, weight=1)
container_settings = tk.Frame(container_main, bg='red', width=300, height=700)
container_settings.pack(side='right', fill='both', expand=True)
container_settings.grid_rowconfigure(0, weight=1)
container_settings.grid_columnconfigure(0, weight=1)
# build settings pages
self.frames = {}
self.frames["Options"] = Options(parent=container_listbox, controller=self)
self.frames["General"] = General(parent=container_settings, controller=self)
self.frames["Future"] = Future(parent=container_settings, controller=self)
如果我取消注释这两行。我收到一条错误消息,说我无法在内部使用几何管理器网格。
# self.frames["General"].grid(row=0, column=0, sticky='nsew')
# self.frames["Future"].grid(row=0, column=0, sticky='nsew')
.
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class Options(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(parent, text='List Box')
label.grid(row=0, column=0, sticky='nsew', padx=1, pady=1)
button1 = tk.Button(parent, text='General', command=lambda: controller.show_frame('General'))
button2 = tk.Button(parent, text='Future', command=lambda: controller.show_frame('Future'))
button1.grid(row=1, column=0, sticky='ew')
button2.grid(row=2, column=0, sticky='ew')
class General(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(parent, text='General')
label.pack(side='left', fill='both', expand=True, )
print("Hi I'm General")
class Future(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(parent, text='Future')
label.pack(side='left', fill='both', expand=True)
print("Hi I'm Future")
app = Settings()
app.mainloop()
两个“页面”同时初始化并显示,这是有道理的。我只是不知道如何让其中一个超越另一个frame.tkraise()
应该这样做,但没有。我也希望能够做到grid_forget()
位于不在顶部的一个或多个页面上,以避免将来可能意外地将值输入到隐藏的输入框中。
编辑:如果我注释掉“未来”页面,那么“常规”页面将占据整个框架空间,因此grid_forget()
我会得到同样的结果。我只是不知道我会去哪里但是grid_forget()
然后我还要在哪里重新配置或执行grid()
call?