【问题标题】:How to equally expand image buttons in Tkinter with grid weight approach?如何使用网格权重方法在 Tkinter 中同样扩展图像按钮?
【发布时间】:2021-05-12 07:41:16
【问题描述】:

我正在尝试使用 tkinter 添加方形按钮。

我知道默认按钮大小是文本(不是像素),因此我应用以下提示来尝试创建方形按钮:

  1. 使用grid_propagate(False) 修复范围帧
  2. 网格columnconfigure(x,weight=1)
  3. 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(...)

标签: python tkinter tk


【解决方案1】:

看看这个。我使用了一个大小为 50 x 50 像素的正方形。

from tkinter import *
from PIL import ImageTk
mainwin=Tk()
f = Frame(mainwin,width=150, height=50, bg = "black")
f.pack()
f.grid_propagate(False)
image1=ImageTk.PhotoImage(file="D:/test/square.png")

Bt1 = Button(f, bg = "#888888",image=image1)
Bt1.grid(row=0,column=0,sticky=N+W+S+E)
Bt2 = Button(f,image=image1, bg = "#AAAAAA")
Bt2.grid(row=0,column=1,sticky=N+W+S+E)
Bt3 = Button(f,image=image1, bg = "#CCCCCC")
Bt3.grid(row=0,column=2,sticky=N+W+S+E)

f.rowconfigure(0,weight=1)
f.columnconfigure(0,weight=1)
f.columnconfigure(1,weight=1)
f.columnconfigure(2,weight=1)

mainwin.mainloop()

【讨论】:

  • 我认为Frame 的宽度应该是 300 而不是 150
  • 我试过PIL模块,结果还是一样。 (您的代码行为正确,因为您在“每个按钮”上应用图像并且您的框架宽度 = 图像大小(50)* 3,您的框架高度 = 图像大小(50)。尝试我的设置,即使您会发现结果仍然失败使用 PIL)
  • 我试过了,没用。这就是为什么我不得不减少框架的宽度
  • 感谢@Sujay 的尝试,但图片尺寸确实比我项目中的按钮小,我认为没有理由修改图片尺寸来填充整个按钮。
猜你喜欢
  • 1970-01-01
  • 2013-03-29
  • 2021-12-19
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 2011-12-05
相关资源
最近更新 更多