为何Tkinter Grid布局中按钮会随标签尺寸变化而拉伸?
问题原因与解决方案
为什么按钮会被拉伸?
Tkinter的Grid布局中,同一列的所有控件共享列宽。当标签文本变长后,列宽会自动调整以适配标签内容。而你的按钮设置了sticky="news",这个属性会让控件填满所在的单元格空间,所以按钮会跟着列宽的变化被拉长成和标签一样的长度。
解决方法
方法1:修改按钮的sticky属性
去掉按钮的sticky="news"(或者改成不填充整个单元格的属性,比如sticky="n"),这样按钮只会保持自身的原始尺寸,不会随列宽变化而拉伸:
import tkinter as tk def change(): label1.config(text = "example text that is really big which shows the button stretching") window = tk.Tk() window.config(bg="black") b1=tk.Button(window,text="button1",font=("Segoe UI",40),command=change) b1.grid(row=1,column=1) # 移除sticky="news",按钮保持原尺寸 label1=tk.Label(text = "text",font=("Segoe UI",20),bg="black",fg="white") label1.grid(row=2,column=1,sticky="news") window.mainloop()
方法2:固定按钮的宽度
创建按钮时指定width参数,强制固定按钮的宽度,即使列宽变化,按钮尺寸也不会改变:
import tkinter as tk def change(): label1.config(text = "example text that is really big which shows the button stretching") window = tk.Tk() window.config(bg="black") # 指定width参数,可根据按钮文本长度调整数值 b1=tk.Button(window,text="button1",font=("Segoe UI",40),command=change, width=8) b1.grid(row=1,column=1,sticky="news") label1=tk.Label(text = "text",font=("Segoe UI",20),bg="black",fg="white") label1.grid(row=2,column=1,sticky="news") window.mainloop()
内容的提问来源于stack exchange,提问作者arandomdeveloper
相关产品推荐
相关产品推荐

