Tkinter Tabcontrol的Example 2标签页无法显示ComboNew组合框
问题定位
Example 2标签页空白核心是两个编写错误,和滚动条框架设计无关:
- 滚动条父组件传参错误:创建Example 2页的垂直滚动条时,父容器填成了第一个Example标签的Frame
a,不是Example 2自身的容器b,滚动条根本没有挂载到当前标签页下 - 缺失布局逻辑:Example 2页创建完canvas、scrollbar控件后,没有调用
pack()方法做布局渲染,控件仅在内存中创建、没有添加到页面视图,因此打开后全空白 - 额外优化:原滚动实现未做宽度自适应、鼠标滚轮支持,修正版补充了这两个常用能力,缩放窗口不会错位,也可以直接用滚轮滚动长内容。
修正后完整可运行代码
from tkinter import ttk import tkinter as tk window = tk.Tk() window.attributes('-zoomed', True) window.configure(bg='#f3f2f2') style = ttk.Style(window) style.theme_use('clam') ####################### tabControl = ttk.Notebook(window, style='Custom.TNotebook', width=700, height=320) cronaca = ttk.Notebook(tabControl) politica = ttk.Notebook(tabControl) gossip = ttk.Notebook(tabControl) tabControl.add(cronaca, text ='Cronaca') tabControl.add(politica, text ='Politica') tabControl.add(gossip, text ='Gossip') tabControl.pack(fill='both', expand=True, padx=1, pady=1) # 替换原place布局,适配窗口缩放 #CRONACA 分类页 incident = ttk.Notebook(cronaca) cronaca.add(incident, text="Incidente") # 通用滚动适配函数 def config_scroll_area(scroll_container): # 传入页容器,返回可放置内容的滚动帧 canvas = tk.Canvas(scroll_container, highlightthickness=0, bg='#f3f2f2') scrollbar = ttk.Scrollbar(scroll_container, orient="vertical", command=canvas.yview) scroll_frame = ttk.Frame(canvas) # 绑定滚动区域 scroll_frame.bind( "<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")) ) # 绑定宽度自适应 canvas_item = canvas.create_window((0, 0), window=scroll_frame, anchor="nw") canvas.bind("<Configure>", lambda e: canvas.itemconfig(canvas_item, width=e.width)) canvas.configure(yscrollcommand=scrollbar.set) # 布局 canvas.pack(side="left", fill="both", expand=True) scrollbar.pack(side="right", fill="y") # 鼠标滚轮绑定(进入页面生效,离开解绑避免冲突) def _on_mousewheel(event): canvas.yview_scroll(int(-1*(event.delta/120)), "units") def _bind_wheel(e): canvas.bind_all("<MouseWheel>", _on_mousewheel) def _unbind_wheel(e): canvas.unbind_all("<MouseWheel>") scroll_container.bind("<Enter>", _bind_wheel) scroll_container.bind("<Leave>", _unbind_wheel) return scroll_frame # Example 标签页 a = ttk.Frame(incident) incident.add(a, text="Example") scroll_frame1 = config_scroll_area(a) combo1=ttk.Combobox(scroll_frame1, width = 18) combo1.place(x=20, y=20) combo1['value'] = ["text1", "text2"] combo2=ttk.Combobox(scroll_frame1, width = 18) combo2.place(x=20, y=80) combo2['value'] = ["text1", "text2"] combo3=ttk.Combobox(scroll_frame1, width = 18) combo3.place(x=20, y=140) combo3['value'] = ["text1", "text2"] combo4=ttk.Combobox(scroll_frame1, width = 18) combo4.place(x=20, y=200) combo4['value'] = ["text1", "text2"] # Example 2 标签页 b = ttk.Frame(incident) incident.add(b, text="Example 2") scroll_frame2 = config_scroll_area(b) comboNew=ttk.Combobox(scroll_frame2, width = 18) comboNew.place(x=20, y=20) comboNew['value'] = ["text1", "text2"] window.mainloop()
内容的提问来源于stack exchange,提问作者user18313765
相关产品推荐
相关产品推荐

