Tkinter Grid布局:如何让Entry组件填满整行并随窗口自适应?
在自定义Tkinter组件中让Entry占据列全部宽度并实现窗口自适应
需求:在自定义的Tkinter组件中,让第二个Entry组件(self.ent_txt)填满所在Frame的全部宽度,并且在窗口大小调整时能自动适配。
修正后的完整代码
import tkinter as tk from tkinter import ttk class MyCustomWidget(ttk.Frame): def __init__(self, master, title=None, *args, **kwargs): super().__init__(master, *args, **kwargs) # 让自定义组件自身的列自适应,确保内部框架能填满空间 self.columnconfigure(0, weight=1) self.title = title self.build_widgets() def build_widgets(self): self.main_frm = ttk.Frame(self) # 让内部框架填满自定义组件的可用空间 self.main_frm.grid(row=0, column=0, sticky=tk.NSEW) idx_column = -1 if self.title is not None: idx_column += 1 ttk.Label(self.main_frm, text=self.title).grid(row=0, column=idx_column) # 给标题列分配固定权重 self.main_frm.columnconfigure(idx_column, weight=1) # 给编码输入框、按钮列分配固定小权重 self.main_frm.columnconfigure(idx_column+1, weight=1) self.main_frm.columnconfigure(idx_column+2, weight=1) # 给目标Entry所在列分配最大权重,让它占据剩余所有空间 self.main_frm.columnconfigure(idx_column+3, weight=10) self.ent_cod = ttk.Entry(self.main_frm, width=10) self.ent_cod.grid(row=0, column=idx_column+1, padx=2, pady=2) self.btn_show_dt = ttk.Button(self.main_frm, text='OK') self.btn_show_dt.grid(row=0, column=idx_column+2, padx=2, pady=2) self.ent_txt = ttk.Entry(self.main_frm) # 设置sticky=tk.EW,让Entry横向填满所在列的宽度 self.ent_txt.grid(row=0, column=idx_column+3, sticky=tk.EW, padx=2, pady=2) if __name__== '__main__': app = tk.Tk() app.geometry('600x200') s = ttk.Style() s.configure('new.TFrame', background='#7AC5CD') frm_main = ttk.Frame(app, style='new.TFrame') frm_main.pack(fill=tk.BOTH, expand=1) frm_container = ttk.Frame(frm_main) frm_container.grid(row=0, column=0, sticky=tk.NSEW) frm_container.columnconfigure(0, weight=1) frm_container.columnconfigure(1, weight=100) ttk.Label(frm_container, text='Test0:').grid(row=0, column=0) ttk.Entry(frm_container).grid(row=0, column=1, sticky=tk.EW) wd_custom = MyCustomWidget(frm_container, title='Test1:') wd_custom.grid(row=1, column=0, columnspan=2, sticky=tk.NSEW) # 让文本框也能纵向自适应窗口大小 text_widget = tk.Text(frm_container) text_widget.grid(row=2, column=0, columnspan=2, sticky=tk.NSEW) frm_container.rowconfigure(2, weight=1) app.mainloop()
核心优化要点
- 给自定义组件
MyCustomWidget自身添加列配置:self.columnconfigure(0, weight=1),保证内部的main_frm能完全填充组件的可用空间。 - 为
main_frm的每一列分配权重:标题、编码输入框、按钮列设为较小的固定权重,目标Entry所在列设为最大权重,让它优先占据剩余空间。 - 给
self.ent_txt的grid方法设置sticky=tk.EW,让Entry横向拉伸填满所在列的宽度。 - 主容器中给文本框所在行添加
rowconfigure(2, weight=1),让文本框也能纵向适配窗口大小。
效果示意图

内容的提问来源于stack exchange,提问作者Mrkalvin Bs
相关产品推荐
相关产品推荐

