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

Tkinter中第二个StringVar无法显示文本问题求助

问题:Tkinter像素编辑器中第二个StringVar无法显示文本

我正在用Tkinter写像素编辑器练GUI编程,打算加个底部框架显示当前工具、画布尺寸这些信息。但第二个定义的StringVar死活显示空白,第一个却正常,代码跑起来没报错。哪怕删掉第一个StringVar,第二个还是没用。底部框架相关代码如下:

# Bottom frame
ttk.Style().configure('Interface.TFrame', background='#dbdbdb')
bottomframe = ttk.Frame(root, style='Interface.TFrame')
bottomframe.grid(column=0, row=2, sticky=(N, S, W, E), pady=4)

# An indicator that shows the current selected tool.
toolname = StringVar()
toolname.set('paint tool')

tool_label = ttk.Label(bottomframe, textvariable=toolname, width=11, background='#dbdbdb', anchor='center')
tool_label.grid(column=0, row=0, sticky=(W, E), padx=2)

# A thin separator.
ttk.Separator(bottomframe, orient=VERTICAL).grid(column=1, row=0, sticky=(N, S, W, E))

# An indicator that shows the canvas size.
cvsize = StringVar()
cvsize.set('50x50 px')

cv_size_label = ttk.Label(bottomframe, textvariable=cvsize, width=11, background='#dbdbdb', anchor='center')
cv_size_label.grid(column=2, row=0, sticky=W, padx=2)

原因分析

问题核心在布局挤压:

  1. 你给垂直分隔符设置了sticky=(N, S, W, E),这会让它尽可能拉伸占满所有可用水平+垂直空间,而bottomframe的列默认没有分配权重,分隔符会直接挤压第三列(画布尺寸标签所在列)的空间,导致标签被挤得完全看不见,看起来像StringVar失效。
  2. 画布尺寸标签的sticky=W只让它靠左对齐,没有设置水平拉伸,一旦列空间被挤压就直接消失,不像第一个标签用sticky=(W, E)能在列内拉伸。

解决方法

1. 调整分隔符的布局属性

去掉分隔符的W和E方向sticky,让它只在垂直方向拉伸,不占用额外水平空间:

ttk.Separator(bottomframe, orient=VERTICAL).grid(column=1, row=0, sticky=(N, S), padx=2)

2. 给框架列设置权重+调整标签sticky

给bottomframe的第0、2列设置权重,让它们能分配到窗口的可用空间,同时把画布尺寸标签的sticky改成(W, E),确保标签能填满列宽:

# 给bottomframe的列分配权重
bottomframe.columnconfigure(0, weight=1)
bottomframe.columnconfigure(2, weight=1)

# 调整画布尺寸标签的grid参数
cv_size_label.grid(column=2, row=0, sticky=(W, E), padx=2)

完整调整后的代码片段

# Bottom frame
ttk.Style().configure('Interface.TFrame', background='#dbdbdb')
bottomframe = ttk.Frame(root, style='Interface.TFrame')
bottomframe.grid(column=0, row=2, sticky=(N, S, W, E), pady=4)
# 新增:给列设置权重
bottomframe.columnconfigure(0, weight=1)
bottomframe.columnconfigure(2, weight=1)

# An indicator that shows the current selected tool.
toolname = StringVar()
toolname.set('paint tool')

tool_label = ttk.Label(bottomframe, textvariable=toolname, width=11, background='#dbdbdb', anchor='center')
tool_label.grid(column=0, row=0, sticky=(W, E), padx=2)

# A thin separator.
# 修改:调整sticky属性
ttk.Separator(bottomframe, orient=VERTICAL).grid(column=1, row=0, sticky=(N, S), padx=2)

# An indicator that shows the canvas size.
cvsize = StringVar()
cvsize.set('50x50 px')

cv_size_label = ttk.Label(bottomframe, textvariable=cvsize, width=11, background='#dbdbdb', anchor='center')
# 修改:调整sticky属性
cv_size_label.grid(column=2, row=0, sticky=(W, E), padx=2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:05:19