微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用网格权重方法同样扩展 Tkinter 中的图像按钮?

如何解决如何使用网格权重方法同样扩展 Tkinter 中的图像按钮?

我正在尝试使用 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()

enter image description here

但是当我在两个按钮上设置图像(50 像素)时,三个按钮的所有宽度都不会同等地扩展。因此,所有按钮都不是方形的。

from tkinter import *

mainwin=Tk()
f = Frame(mainwin,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,bg = "#AAAAAA",compound='c')
Bt2["image"] = test_image
Bt2.grid(row=0,bg = "#CCCCCC",compound='c')
Bt3.grid(row=0,weight=1)

mainwin.mainloop()

enter image description here

我猜所有按钮的“初始宽度”将按 (300-50*2)/3 计算, 然后是按钮的“最终宽度”,图像 = 初始宽度 + 其图像宽度

在上面的情况下最终宽度= 115,115,70。对于那个115-50(图像大小)= 65接近70,差异可能与边界或填充有关...

如何通过应用网格权重方法将图像按钮同样扩展为方形?

解决方法

看看这个。我使用了一个大小为: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,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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。