You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python文本编辑器:Toplevel窗口添加的Widgets为何不显示?

解决Tkinter偏好设置窗口控件不显示问题

你的代码存在几个导致控件无法正常显示的问题,对应修复方案如下:

问题点与修复

  • 无效的控件尺寸参数:Menubutton的height=0.1是错误设置,Tkinter中按钮的height指字符行数,必须为正整数,小数会导致控件渲染失败。将其改为height=1即可。
  • 布局权重未配置:主窗口pref_window和容器menuframe没有设置布局权重,导致容器无法填充窗口空间,控件被挤压隐藏。通过columnconfigure和rowconfigure设置权重,让布局自动扩展。
  • 冗余的尺寸设置:Frame的width和height在grid布局下会被自动忽略,无需手动设置,改为通过sticky="nsew"让容器填充父窗口。

修改后的完整代码

def OpenPrefs():
    pref_window = Toplevel()
    pref_window.title("TextWrite - Preferences")
    pref_window.geometry("400x225")
    
    # 配置主窗口布局权重,让子控件填充窗口
    pref_window.columnconfigure(0, weight=1)
    pref_window.rowconfigure(0, weight=1)

    menuframe = Frame(pref_window)
    # 让Frame填充整个主窗口
    menuframe.grid(row=0, column=0, sticky="nsew")
    # 配置Frame内部布局权重
    menuframe.columnconfigure(0, weight=1)
    menuframe.rowconfigure(0, weight=1)

    global theme_btn
    global theme_menu

    # 修正height为有效正整数,添加边距优化显示
    theme_btn = Menubutton(menuframe, width=10, height=1, text="Theme")
    theme_btn.grid(row=0, column=0, sticky=W, padx=10, pady=10)

    theme_menu = Menu(theme_btn, tearoff=0)
    theme_btn.config(menu=theme_menu)

    theme_menu.add_command(label="Light")
    theme_menu.add_command(label="Dark")

内容的提问来源于stack exchange,提问作者Sebwazhere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:57:42