按钮的宽度以字符宽度为单位进行定义。在你的情况下,按钮被定义为17个字符宽。所以通过改变字符宽度(即改变字体大小)来改变按钮的宽度。 AFAIK,唯一的解决方法是将按钮放入一个Frame中,因为Frame可以用像素来定义它的大小。这里有一个新的按钮的那正是这么做的:
import Tkinter as tk
class Warspyking(tk.Frame):
'''A button that has it's width and height set in pixels'''
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master)
self.rowconfigure(0, minsize=kwargs.pop('height', None))
self.columnconfigure(0, minsize=kwargs.pop('width', None))
self.btn = tk.Button(self, **kwargs)
self.btn.grid(row=0, column=0, sticky="nsew")
self.config = self.btn.config
#example usage:
MyWindow = tk.Tk()
MyWindow.geometry("500x550")
from itertools import cycle
fonts = cycle((('Helvetica', '11'),('Helvetica', '15'),('Helvetica', '20')))
def chg():
button.config(font=next(fonts))
button = Warspyking(MyWindow,text="Click me!",width=200,height=100 ,font=next(fonts), command=chg)
button.grid(row=1, column=1)
MyWindow.mainloop()
编辑:基于我从布莱恩·奥克利了解到,这里有一个更整洁的实现:
class Warspyking(tk.Button):
def __init__(self, master=None, **kwargs):
self.img = tk.PhotoImage()
tk.Button.__init__(self, master, image=self.img, compound='center', **kwargs)
我还要补充一点,我很同意布莱恩:使用这可能表明你做错了什么。你应该让tkinter处理大小。
为什么你将字号传递为字符串而不是数字? – martineau
@martineau嗯,我通过它的方式其实并不重要,但我想我在网上发现了通过它的文档。 – warspyking
尽管如此,它并没有帮助我解决手头上的真实问题 – warspyking