Tkinter pack布局问题:如何让底部框架紧贴Notebook组件?
Tkinter Notebook 下方框架布局问题解决方案
问题描述
在提供的Tkinter代码中,Notebook组件通过pack(side="top", anchor="n", expand=True)布局,底部的bottom_frame使用pack(side="top", anchor="n", fill="x")布局,但该框架并未紧贴Notebook,而是停靠在窗口底部。需要调整布局让框架直接位于Notebook组件下方。
解决思路与修改方法
问题出在Notebook的expand=True参数上——这个参数会让Notebook占据窗口内所有剩余的垂直空间,把bottom_frame挤到了窗口底部。调整方式如下:
- 移除
Notebook的expand=True参数(或设为expand=False),如果需要Notebook填充水平宽度,可添加fill="x"参数 - 保持
bottom_frame的pack调用在Notebook之后,维持fill="x"让它铺满窗口水平方向
修改后的完整代码
import tkinter as tk from tkinter import ttk class App(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.create_widgets() def create_widgets(self): self.notebook = ttk.Notebook(self.master) # 移除expand=True,添加fill="x"让Notebook填充水平宽度 self.notebook.pack(side="top", anchor="n", fill="x") # create tabs self.tabs = {} self.tabs["tab1"] = tk.Frame(self.notebook, width=420, height=420, borderwidth=0) self.tabs["tab2"] = tk.Frame(self.notebook, width=420, height=420, borderwidth=0) self.tab_headers = ["tab1", "tab2"] self.tabs["tab1"].pack() self.tabs["tab2"].pack() # add frame with label below notebook self.bottom_frame = tk.Frame(self.master, bg="#ffff00") self.bottom_frame.pack(side="top", anchor="n", fill="x") self.bottom_label = tk.Label(self.bottom_frame, text="This is a label below the notebook", font=("TkDefaultFont", 14), bg="#ffff00") self.bottom_label.pack(side="top", pady=10) # add tabs to notebook self.notebook.add(self.tabs["tab1"], text='Tab 1') self.notebook.add(self.tabs["tab2"], text='Tab 2') root = tk.Tk() root.geometry("420x840") root.resizable(False, False) app = App(master=root) app.mainloop()
内容的提问来源于stack exchange,提问作者Yudhishthira Dattachaudhuri
相关产品推荐
相关产品推荐

