Python3:如何动态调整中的Tkinter / TTK按钮上的文字? [英] Python3: How to dynamically resize button text in tkinter/ttk?

查看:2352
本文介绍了Python3:如何动态调整中的Tkinter / TTK按钮上的文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何为一个TTK小部件(标签或按钮,说的)文本安排自动调整。

I want to know how to arrange for the text on a ttk widget (a label or button, say) to resize automatically.

更改文本的大小很容易,它只是一个在样式更改字体的问题。然而,它挂钩到窗口大小的变化是一个小更棘手。展望在网络上我发现了一些线索,但无处一个完整的答案被张贴。

Changing the size of the text is easy, it is just a matter of changing the font in the style. However, hooking it into changes in the size of the window is a little more tricky. Looking on the web I found some hints, but there was nowhere a complete answer was posted.

所以,这里是下面张贴的答案,我自己的问题一个完整的工作示例。我希望有人发现它是有用的。如果任何人有进一步的改善建议,我会很高兴看到他们!

So, here below is a complete working example posted as an answer to my own question. I hope someone finds it useful. If anyone has further improvements to suggest, I will be delighted to see them!

推荐答案

下面的例子显示了两个方法,一是通过重新调整大小的窗口(请参阅调整()方法,绑定到<配置及GT; 事件),以及其他直接更改字体的大小(请参阅突变()方法)。

The example below shows two techniques, one activated by re-sizing the window (see the resize() method, bound to the <Configure> event), and the other by directly changing the size of the font (see the mutate() method).

必要得到调整工作的其他code是在网格配置code中的 __ __的init()方法。

Other code necessary to get resizing working is the grid configuration code in the __init__() method.

运行示例时,有两种方法之间的一些互动,但我认为一个'真正'的情况的一种方法就足够了,这样的问题不会出现。

When running the example, there is some interaction between the two methods, but I think in a 'real' situation one technique would be sufficient, so that issue won't arise.

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()

这篇关于Python3:如何动态调整中的Tkinter / TTK按钮上的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆