Tkinter向frameSystemInfo框架添加控件后布局崩坏如何解决
调整方案
布局崩坏核心原因是frameSystemInfo内部的网格权重配置错误,导致内部控件拉伸时带动外层主窗口布局异常,按以下规则调整即可:
frameSystemInfo仅需要列0设权重1,保证内部控件横向撑满容器frameSystemInfo的行权重仅给最底部的空白行设为1,上方的label、entry、按钮行不设权重,避免内部控件高度被强制拉伸- 三个按钮所在行的3个列分别设权重1,保证三个按钮均分宽度
- 控件的sticky属性根据展示需求配置,避免不必要的拉伸
完整可运行代码
import tkinter as tk windowBackgroundColor = "#333333" cardColor = "#000000" textColor = "#ffffff" class SystemInfoView(): def __init__(self, root): self.root = root def initializeView(self): self.frameSystemInfo = tk.Frame(self.root, bg=cardColor) self.frameSystemInfo.grid(column=0, row=0, rowspan=2, sticky="NSEW", padx=5, pady=5) # 配置内部列权重,保证内容横向撑满 self.frameSystemInfo.columnconfigure(0, weight=1) self.frameSystemInfo.columnconfigure(1, weight=1) self.frameSystemInfo.columnconfigure(2, weight=1) # 仅底部空白行设权重,占满剩余高度 self.frameSystemInfo.rowconfigure(3, weight=1) # 系统时间标签,左对齐 labelSystemTime = tk.Label(self.frameSystemInfo, text="System Time:", fg=textColor, bg=cardColor) labelSystemTime.grid(column=0, row=0, columnspan=3, sticky="W", padx=10, pady=(10,5)) # 输入框,横向撑满 entrySystemTime = tk.Entry(self.frameSystemInfo, font=("Helvetica", 14)) entrySystemTime.grid(column=0, row=1, columnspan=3, sticky="EW", padx=10, pady=(0,10)) # 三个并排按钮,均分宽度 btn1 = tk.Button(self.frameSystemInfo, text="按钮1") btn1.grid(column=0, row=2, sticky="EW", padx=5, pady=2) btn2 = tk.Button(self.frameSystemInfo, text="按钮2") btn2.grid(column=1, row=2, sticky="EW", padx=5, pady=2) btn3 = tk.Button(self.frameSystemInfo, text="按钮3") btn3.grid(column=2, row=2, sticky="EW", padx=5, pady=2) class App(tk.Tk): def __init__(self): super().__init__() self.title("My Title") self.geometry("800x600") self.configure(bg=windowBackgroundColor) self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) self.columnconfigure(2, weight=1) self.columnconfigure(3, weight=1) self.rowconfigure(0, weight=1) self.rowconfigure(1, weight=1) self.rowconfigure(2, weight=1) self.systemInfoView = SystemInfoView(self) self.systemInfoView.initializeView() rectangle_2 = tk.Frame(self, bg="#000000") rectangle_2.grid(column=1, row=0, sticky="NSEW", padx=5, pady=5) rectangle_3 = tk.Frame(self, bg="#000000") rectangle_3.grid(column=2, row=0, sticky="NSEW", padx=5, pady=5) rectangle_4 = tk.Frame(self, bg="#000000") rectangle_4.grid(column=3, row=0, sticky="NSEW", padx=5, pady=5) if __name__ == "__main__": app = App() app.mainloop()
内容的提问来源于stack exchange,提问作者Qwe Qwe
相关产品推荐
相关产品推荐

