如何让Tkinter中的Frame填充所在整列?
问题
使用Tkinter开发简易GUI,当前布局包含权重分别为1和2的两列,希望添加的两个ConfigCreator组件(cfg和cfgx)能够填满各自所在的整列,基于现有代码该如何实现?
解决方案
要让组件填满所在列,核心是利用Tkinter的grid布局sticky参数,结合已配置的列权重实现拉伸:
- 在放置ConfigCreator组件时,给
grid()方法添加sticky="nsew"参数,让组件沿着单元格的北、南、东、西四个方向拉伸,完全填满所在单元格。 - 现有代码中已正确配置列权重(
columnconfigure),且MainApplication通过pack(fill="both", expand=True)填满根窗口,这部分无需修改。
若后续给ConfigCreator添加子组件,还需给ConfigCreator自身配置布局权重(比如self.columnconfigure(0, weight=1)),确保子组件也能填满容器;但仅实现当前需求的话,只需修改组件的grid调用即可。
修改后的完整代码
主程序代码
import tkinter as tk from components.ConfigCreator import ConfigCreator WIDTH = 800 HEIGHT = 600 POS_X = 300 POS_Y = 200 class MainApplication(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self._setup_size_and_positioning() self._setup_layout() self._setup_widgets() def _setup_size_and_positioning(self) -> None: self.winfo_toplevel().title('Test app') self.winfo_toplevel().geometry(f"{WIDTH}x{HEIGHT}+{POS_X}+{POS_Y}") self.config(width=WIDTH, height=HEIGHT) def _setup_layout(self) -> None: # 注:该行可删除,因为MainApplication已通过pack布局到root中 # self.grid(row=0, column=0) self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=2) def _setup_widgets(self) -> None: cfg = ConfigCreator(self) # 添加sticky参数让组件填满单元格 cfg.grid(row=0, column=0, sticky="nsew") cfg.config(bg="limegreen") cfgx = ConfigCreator(self) # 添加sticky参数让组件填满单元格 cfgx.grid(row=0, column=1, sticky="nsew") cfgx.config(bg="skyblue") if __name__ == "__main__": root = tk.Tk() MainApplication(root).pack(side="top", fill="both", expand=True) root.mainloop()
ConfigCreator.py代码
import tkinter as tk class ConfigCreator(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) # 若后续添加子组件,可在此配置内部布局权重,例如: # self.columnconfigure(0, weight=1) # self.rowconfigure(0, weight=1)
内容的提问来源于stack exchange,提问作者Jakub Sapko
相关产品推荐
相关产品推荐

