如何显示正方形的Tkinter.Button?

5 投票
3 回答
10907 浏览
提问于 2025-04-18 06:50

为什么这段代码显示的按钮比宽度还要高呢?

import Tkinter, tkFont
top = Tkinter.Tk()
right = Tkinter.Frame(top)
right.pack(side = "right")
font = tkFont.Font(family="Helvetica", size=60, weight = tkFont.BOLD)

for i in xrange(6):
    b = Tkinter.Button(right, text = str(i), font = font, width = 1, height = 1)
    top.rowconfigure(i, weight = 1)
    top.columnconfigure(i, weight = 1)
    b.grid(row = i/3, column = i%3, sticky = "NWSE")

top.mainloop()
  • 所有按钮都是用 width=1, height=1 创建的。
  • 对于每一行和每一列的 right,都有调用 right.rowconfigure(rowi, weight=1)(或者 columnconfigure)。
  • 每个按钮 b 的网格放置都是用的粘性 NSEW
  • 我设置了 right.grid_propagate(0)

我到底做错了什么呢?

如果我把按钮直接放到 top 上,按钮就会变得比高还要宽。看起来它们是被调整大小以适应传播的空间。我该如何防止这种调整大小呢?

3 个回答

0

这是因为5x5并不是表示5个像素乘以5个像素,而是表示5个零乘以5个零。

它表示的是这个:

00000
0
0
0
0
4

另一种方法是让 Button 误以为它正在显示一张图片,这样它的单位就可以用像素来调整,而不是用文字大小。

你可以通过创建一个空的 PhotoImage 实例,把它设置为按钮的 image 选项,然后使用按钮的 compound 选项来把“图片”和文字结合在一起。下面是一个使用你代码的一部分的例子:

import Tkinter, tkFont


root = Tkinter.Tk()

font = tkFont.Font(family="Helvetica", size=60, weight = tkFont.BOLD)
blank_image = Tkinter.PhotoImage()

for i in xrange(6):
    b = Tkinter.Button(root, image=blank_image, text=str(i),
                       font=font, compound=Tkinter.CENTER)

    # get the height of the font to use as the square size
    square_size = font.metrics('linespace')
    b.config(width=square_size, height=square_size)

    b.grid(row = i/3, column = i%3, sticky = "NWSE")

root.mainloop()
9

如果一个 Button 按钮上显示了文字,当你使用 heightwidth 选项时,这些单位是以文字的单位来计算的。为了让按钮变成正方形,使用像素单位会更好。要做到这一点,你需要把这个按钮放在一个 Frame 框架里,并确保这个框架不会自动调整大小(grid_propagate),同时允许它里面的内容填满这个框架(columnconfigurerowconfigure)。

这只是一个例子,因为我看不到你的代码。

import Tkinter as tk

master = tk.Tk()

frame = tk.Frame(master, width=40, height=40) #their units in pixels
button1 = tk.Button(frame, text="btn")


frame.grid_propagate(False) #disables resizing of frame
frame.columnconfigure(0, weight=1) #enables button to fill frame
frame.rowconfigure(0,weight=1) #any positive number would do the trick

frame.grid(row=0, column=1) #put frame where the button should be
button1.grid(sticky="wens") #makes the button expand

tk.mainloop()

编辑:我刚看到你更新了内容(添加了你的代码)。在你的代码上应用相同的设置后;

import Tkinter, tkFont
top = Tkinter.Tk()
right = Tkinter.Frame(top)
right.pack(side = "right")
font = tkFont.Font(family="Helvetica", size=20, weight = tkFont.BOLD)

for i in xrange(6):
    f = Tkinter.Frame(right,width=50,height=50)
    b = Tkinter.Button(f, text = str(i), font = font)

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

    f.grid(row = i/3, column = i%3)
    b.grid(sticky = "NWSE")

top.mainloop()

撰写回答