通常,当您为按钮指定宽度时,该宽度以字符为单位进行测量(即:width=1
指一个平均大小字符的宽度)。但是,如果按钮有图像,则宽度指定以像素为单位的大小。
按钮可以同时包含图像和文本,因此一种策略是将 1x1 像素作为图像,以便您可以以像素为单位指定按钮大小。当您这样做并更改字体大小时,按钮将不会变大,因为它被赋予了绝对大小。
下面是一个说明该技术的示例。运行代码,然后单击“更大”或“更小”,可以看到文本大小发生变化,但按钮没有变化。
import Tkinter as tk
import tkFont
def bigger():
size = font.cget("size")
font.configure(size=size+2)
def smaller():
size = font.cget("size")
size = max(2, size-2)
font.configure(size=size)
root = tk.Tk()
font = tkFont.Font(family="Helvetica", size=12)
toolbar = tk.Frame(root)
container = tk.Frame(root)
toolbar.pack(side="top", fill="x")
container.pack(side="top", fill="both", expand=True)
bigger = tk.Button(toolbar, text="Bigger", command=bigger)
smaller = tk.Button(toolbar, text="Smaller", command=smaller)
bigger.pack(side="left")
smaller.pack(side="left")
pixel = tk.PhotoImage(width=1, height=1)
for row in range(3):
container.grid_rowconfigure(row, weight=1)
for column in range(3):
container.grid_columnconfigure(column, weight=1)
button = tk.Button(container, font=font, text="x",
image=pixel, compound="center", width=20, height=20)
button.grid(row=row, column=column)
root.mainloop()
话虽如此,这几乎从来都不是一个好主意。如果用户想要更大的字体,整个用户界面应该适应。 Tkinter 确实很擅长实现这一点,以至于默认情况下一切都可以正常工作。