尝试调整Tkinter中ttk.Button大小报错:未知-height属性
错误原因
你使用的ttk.Button并不支持直接通过height和width参数设置尺寸,这两个参数是原生tk.Button的专属属性。ttk组件采用样式系统管理外观与尺寸配置,直接传入这两个参数会触发TclError。
两种修复方案
方案一:改用原生tk.Button
如果不需要ttk的主题样式,直接替换成tk.Button即可,原代码的height和width参数可正常使用:
import tkinter as tk import random window = tk.Tk() def moved(e): myx = e.x myy = e.y mylbl.place(x=myx - 20, y=myy - 20) def randomsize(): size = random.randrange(20, 200) sizey = size * 2 mylbl.config(width=sizey, height=size) # 替换为tk.Button mylbl = tk.Button(window, text="Hello", command=randomsize, height=30, width=60) mylbl.place(x=10, y=10) window.bind("<Motion>", moved) window.mainloop()
方案二:用ttk.Style配置ttk.Button尺寸
如果要保留ttk的样式,需通过ttk.Style定义按钮样式,调整内边距或字体大小控制尺寸,同时修改randomsize函数通过样式更新尺寸:
import tkinter as tk from tkinter import ttk import random window = tk.Tk() # 创建并配置ttk样式 style = ttk.Style() style.configure('Custom.TButton', padding=(30, 15)) # 用padding控制按钮大小 def moved(e): myx = e.x myy = e.y mylbl.place(x=myx - 40, y=myy - 20) # 调整偏移量适配新尺寸 def randomsize(): pad_x = random.randrange(20, 100) pad_y = random.randrange(10, 50) style.configure('Custom.TButton', padding=(pad_x, pad_y)) # 使用自定义样式的ttk.Button mylbl = ttk.Button(window, text="Hello", command=randomsize, style='Custom.TButton') mylbl.place(x=10, y=10) window.bind("<Motion>", moved) window.mainloop()
注意:ttk组件的
config方法也不支持直接设置height/width,随机调整尺寸时需通过修改样式的padding或字体实现。
内容的提问来源于stack exchange,提问作者Andre
相关产品推荐
相关产品推荐

