CustomTkinter中TabView嵌入CTkFrame宽高不生效问题求助
解决CustomTkinter TabView中CTkFrame宽高参数不生效的问题
问题出在pack布局的默认行为和组件尺寸传播机制上:CustomTkinter的CTkFrame继承自tkinter.Frame,默认会根据子组件大小自动调整自身尺寸;同时TabView的标签页容器也需要允许内部组件展开。以下是具体修复方案:
核心修改点
- 禁用Frame的尺寸自动传播:调用
frame.pack_propagate(False),让Frame保持你设置的宽高,不受子组件尺寸影响。 - 调整Frame的pack参数:添加
fill="both"和expand=True,让Frame填充Tab标签页的可用空间(如果需要固定大小,可省略这两个参数,仅保留pack_propagate(False))。
修改后的完整代码
class MyApp: def FillFirstTab(self, tab): frame = CTkFrame(master=tab, corner_radius=10, border_width=2, width=500, height=500) # 禁用Frame根据子组件自动调整尺寸 frame.pack_propagate(False) entry = CTkEntry(frame, placeholder_text="CTkEntry", width=200) xImg = xCircleSmall() btn = CTkButton(frame, text="Click Me", image=CTkImage(dark_image=xImg.getObject(), light_image=xImg.getObject()), command=buttonEvent, corner_radius=10, border_width=0, border_color="#000000") entry.pack(padx=10, pady=10) btn.place(relx=0.5, rely=1, anchor="center") # 调整pack参数,让Frame填充Tab空间(固定大小则改为frame.pack(padx=10, pady=10)) frame.pack(padx=10, pady=10, fill="both", expand=True) def __init__(self, width, height): self.app = CTk() self.app.title("My App") self.app.geometry(f"{width}x{height}") set_appearance_mode("default") tabView = CTkTabview(self.app, width=width, height=height) # 让TabView填充窗口可用空间 tabView.pack(padx=10, pady=10, fill="both", expand=True) tabView.add("Tab 1") tabView.add("Tab 2") tabView.add("Tab 3") self.FillFirstTab(tabView.tab("Tab 1")) if __name__ == "__main__": width = int(get_monitors()[0].width * 0.9) height = int(get_monitors()[0].height * 0.9) app = MyApp(width, height).app app.mainloop()
额外说明
- 如果需要固定Frame为500x500,只需保留
frame.pack_propagate(False),并将frame.pack(...)改为frame.pack(padx=10, pady=10)即可,此时Frame不会随窗口缩放。 - TabView本身添加
fill="both"和expand=True,是为了确保它能填充窗口的可用空间,避免标签页容器过小限制Frame的显示。
内容的提问来源于stack exchange,提问作者Lilmark0o
相关产品推荐
相关产品推荐

