Button Python3:如何在tkinter/ttk中动态调整按钮文本的大小?

Button Python3:如何在tkinter/ttk中动态调整按钮文本的大小?,button,resize,python-3.x,tkinter,ttk,Button,Resize,Python 3.x,Tkinter,Ttk,我想知道如何安排ttk小部件(比如标签或按钮)上的文本自动调整大小 更改文本的大小很容易,只需更改样式中的字体即可。然而,将其与窗口大小的变化挂钩有点棘手。我在网上找到了一些提示,但是没有一个完整的答案被公布 下面是一个完整的工作示例,作为对我自己问题的回答。我希望有人觉得它有用。如果有人有进一步的改进建议,我将很高兴看到他们 下面的示例显示了两种技术,一种是通过重新调整窗口大小激活的(请参见绑定到事件的resize()方法),另一种是通过直接更改字体大小激活的(请参见mutate()方法) 调

我想知道如何安排ttk小部件(比如标签或按钮)上的文本自动调整大小

更改文本的大小很容易,只需更改样式中的字体即可。然而,将其与窗口大小的变化挂钩有点棘手。我在网上找到了一些提示,但是没有一个完整的答案被公布


下面是一个完整的工作示例,作为对我自己问题的回答。我希望有人觉得它有用。如果有人有进一步的改进建议,我将很高兴看到他们

下面的示例显示了两种技术,一种是通过重新调整窗口大小激活的(请参见绑定到
事件的
resize()
方法),另一种是通过直接更改字体大小激活的(请参见
mutate()
方法)

调整大小所需的其他代码是
\uuuu init\uuu()
方法中的网格配置代码

在运行该示例时,这两种方法之间存在一些交互,但我认为在“真实”情况下,一种技术就足够了,这样就不会出现问题

from tkinter import *
from tkinter.ttk import *


class ButtonApp(Frame):
    """Container for the buttons."""

    def __init__(self, master=None):
        """Initialize the frame and its children."""

        super().__init__(master)
        self.createWidgets()

        # configure the frame's resize behaviour
        master.columnconfigure(0, weight=1)
        master.rowconfigure(0, weight=1)
        self.grid(sticky=(N,S,E,W))

        # configure resize behaviour for the frame's children
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # bind to window resize events
        self.bind('<Configure>', self.resize)


    def createWidgets(self):
        """Make the widgets."""

        # this button mutates
        self.mutantButton = Button(self, text='Press Me',
                                   style='10.TButton')
        self.mutantButton.grid(column=0, row=0, sticky=(N,S,E,W))
        self.mutantButton['command'] = self.mutate

        # an ordinary quit button for comparison
        self.quitButton = Button(self, text='Quit', style='TButton')
        self.quitButton.grid(column=0, row=1, sticky=(N,S,E,W))
        self.quitButton['command'] = self.quit


    def mutate(self):
        """Rotate through the styles by hitting the button."""

        style = int(self.mutantButton['style'].split('.')[0])
        newStyle = style + 5
        if newStyle > 50: newStyle = 10
        print('Choosing font '+str(newStyle))
        self.mutantButton['style'] = fontStyle[newStyle]

        # resize the frame

        # get the current geometries
        currentGeometry = self._root().geometry()
        w, h, x, y = self.parseGeometry(currentGeometry)
        reqWidth = self.mutantButton.winfo_reqwidth()
        reqHeight = self.mutantButton.winfo_reqheight()

        # note assume height of quit button is constant at 20.
        w = max([w, reqWidth])
        h = 20 + reqHeight
        self._root().geometry('%dx%d+%d+%d' % (w, h, x, y))


    def parseGeometry(self, geometry):
        """Geometry parser.
        Returns the geometry as a (w, h, x, y) tuple."""

        # get w
        xsplit = geometry.split('x')
        w = int(xsplit[0])
        rest = xsplit[1]

        # get h, x, y
        plussplit = rest.split('+')
        h = int(plussplit[0])
        x = int(plussplit[1])
        y = int(plussplit[2])

        return w, h, x, y


    def resize(self, event):
        """Method bound to the <Configure> event for resizing."""

        # get geometry info from the root window.
        wm, hm = self._root().winfo_width(), self._root().winfo_height()

        # choose a font height to match
        # note subtract 30 for the button we are NOT scaling.
        # note we assume optimal font height is 1/2 widget height.
        fontHeight = (hm - 20) // 2
        print('Resizing to font '+str(fontHeight))

        # calculate the best font to use (use int rounding)
        bestStyle = fontStyle[10] # use min size as the fallback
        if fontHeight < 10: pass # the min size
        elif fontHeight >= 50: # the max size
            bestStyle = fontStyle[50]
        else: # everything in between
            bestFitFont = (fontHeight // 5) * 5
            bestStyle = fontStyle[bestFitFont]

        # set the style on the button
        self.mutantButton['style'] = bestStyle


root = Tk()
root.title('Alice in Pythonland')

# make a dictionary of sized font styles in the range of interest.
fontStyle = {}
for font in range(10, 51, 5):
    styleName = str(font)+'.TButton'
    fontName = ' '.join(['helvetica', str(font), 'bold'])
    fontStyle[font] = styleName
    Style().configure(styleName, font=fontName)

# run the app
app = ButtonApp(master=root)
app.mainloop()
root.destroy()
从tkinter导入*
从tkinter.ttk导入*
类按钮(框架):
“”“按钮的容器。”“”
def uuu init uuu(self,master=None):
“”“初始化框架及其子项。”“”
超级()。\uuuu初始化\uuuuu(主)
self.createWidgets()
#配置框架的调整大小行为
master.columnconfigure(0,权重=1)
master.rowconfigure(0,权重=1)
自网格(粘性=(N,S,E,W))
#为框架的子对象配置调整大小行为
self.columnconfigure(0,权重=1)
self.rowconfigure(0,权重=1)
self.rowconfigure(0,权重=1)
#绑定到窗口大小调整事件
self.bind(“”,self.resize)
def createWidgets(自):
“”“制作小部件。”“”
#这个按钮变异了
self.mutantButton=按钮(self,text='Press Me',
style='10.TButton')
self.mutantButton.grid(列=0,行=0,粘性=(N,S,E,W))
self.mutatButton['command']=self.mutate
#用于比较的普通退出按钮
self.quitButton=按钮(self,text='Quit',style='TButton')
self.quitButton.grid(列=0,行=1,粘性=(N,S,E,W))
self.quit按钮['command']=self.quit
def变异(自身):
“”“通过点击按钮旋转样式。”“”
style=int(self.mutantButton['style'].split('..')[0])
新闻风格=风格+5
如果newStyle>50:newStyle=10
打印('选择字体'+str(新闻样式))
self.muntatbutton['style']=fontStyle[newStyle]
#调整框架的大小
#获取当前几何图形
currentGeometry=self.\u root().geometry()
w、 h,x,y=自解析几何体(currentGeometry)
reqWidth=self.mutanbutton.winfo_reqWidth()
reqHeight=self.mutanbutton.winfo_reqHeight()
#注意:假设退出按钮的高度恒定为20。
w=最大值([w,要求宽度])
h=20+1高
self._root().geometry(“%dx%d+%d+%d%”(w,h,x,y))
定义解析几何体(自身,几何体):
“几何体分析器。
以(w,h,x,y)元组的形式返回几何体。”“”
#得到w
xsplit=geometry.split('x')
w=int(xsplit[0])
rest=xsplit[1]
#得到h,x,y
plussplit=rest.split(“+”)
h=int(plussplit[0])
x=int(plussplit[1])
y=int(plussplit[2])
返回w,h,x,y
def调整大小(自身、事件):
“”“方法绑定到事件以调整大小。”“”
#从根窗口获取几何体信息。
wm,hm=self.\u root().winfo\u width(),self.\u root().winfo\u height()
#选择要匹配的字体高度
#注:按钮减去30,我们不缩放。
#注意:我们假设最佳字体高度为小部件高度的1/2。
fontHeight=(hm-20)//2
打印('调整字体大小'+str(字体高度))
#计算要使用的最佳字体(使用整数舍入)
bestStyle=fontStyle[10]#使用最小大小作为后备
如果字体高度<10:通过#最小尺寸
elif fontHeight>=50:#最大尺寸
bestStyle=fontStyle[50]
其他:#介于两者之间的一切
bestFitFont=(fontHeight//5)*5
bestStyle=fontStyle[bestFitFont]
#在按钮上设置样式
self.mutantButton['style']=bestStyle
root=Tk()
root.title('Alice in Pythonland')
#制作感兴趣范围内大小字体样式的词典。
fontStyle={}
对于范围(10、51、5)内的字体:
styleName=str(字体)+'.TButton'
fontName=''.join(['helvetica',str(font),'bold']))
fontStyle[font]=样式名
Style().configure(styleName,font=fontName)
#运行应用程序
app=ButtonApp(master=root)
app.mainloop()
root.destroy()