【发布时间】:2021-05-12 07:41:16
【问题描述】:
我正在尝试使用 tkinter 添加方形按钮。
我知道默认按钮大小是文本(不是像素),因此我应用以下提示来尝试创建方形按钮:
- 使用
grid_propagate(False)修复范围帧 - 网格
columnconfigure(x,weight=1) - 按
sticky=W+E+S+N展开按钮。
以下情况(没有图像的按钮)很好。三个按钮的所有宽度均等扩展为 100。因此所有按钮都是 100x100 正方形。
from tkinter import *
mainwin=Tk()
f = Frame(mainwin,width=300, height=100, bg = "black")
f.pack()
f.grid_propagate(False)
Bt1 = Button(f, bg = "#888888")
Bt1.grid(row=0,column=0,sticky=W+E+S+N)
Bt2 = Button(f, bg = "#AAAAAA")
Bt2.grid(row=0,column=1,sticky=W+E+S+N)
Bt3 = Button(f, bg = "#CCCCCC")
Bt3.grid(row=0,column=2,sticky=W+E+S+N)
f.rowconfigure(0,weight=1)
f.columnconfigure(0,weight=1)
f.columnconfigure(1,weight=1)
f.columnconfigure(2,weight=1)
mainwin.mainloop()
但是,当我在两个按钮上设置图像(50 像素)时,三个按钮的所有宽度都不会平均扩展。因此不是所有的按钮都是方形的。
from tkinter import *
mainwin=Tk()
f = Frame(mainwin,width=300, height=100, bg = "black")
f.pack()
f.grid_propagate(False)
test_image = PhotoImage(file="test_50x50.png")
Bt1 = Button(f, bg = "#888888", compound='c')
Bt1["image"] = test_image
Bt1.grid(row=0,column=0,sticky=W+E+S+N)
Bt2 = Button(f, bg = "#AAAAAA", compound='c')
Bt2["image"] = test_image
Bt2.grid(row=0,column=1,sticky=W+E+S+N)
Bt3 = Button(f, bg = "#CCCCCC", compound='c')
Bt3.grid(row=0,column=2,sticky=W+E+S+N)
f.rowconfigure(0,weight=1)
f.columnconfigure(0,weight=1)
f.columnconfigure(1,weight=1)
f.columnconfigure(2,weight=1)
mainwin.mainloop()
我猜所有按钮的“初始宽度”将按 (300-50*2)/3 计算, 然后是按钮的“最终宽度”,图像 = 初始宽度 + 其图像宽度
在上述情况下,最终宽度 = 115, 115, 70。因为 115-50(图像大小) = 65 接近 70,差异可能与边界或填充有关...
如何通过应用网格权重方法将图像按钮同样扩展为方形?
【问题讨论】:
-
将
uniform=1添加到所有f.columnconfigure(...)。