在wxPython中查找文本大小的正确方法 [英] The right way to find the size of text in wxPython

查看:176
本文介绍了在wxPython中查找文本大小的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在wxPython中开发的应用程序.该应用程序的一部分在一个网格中创建了大量TextCtrl,以便在一周中的每一天为任意数量的人员列表输入四个字母的代码.

I have an application I am developing in wxPython. Part of the application creates a large number of TextCtrls in a grid in order to enter four-letter codes for each day of the week for an arbitrarily large list of people.

我设法使它起作用,但是我不得不做一些笨拙的事情.具体来说,我还没有找到一种好的方法来计算文本的大小(以像素为单位),因此我不得不猜测要调整TextCtrl的大小以使其适合最大(4个字母)的代码.我担心的是,如果要更改文本的大小,或者将应用程序移植到MSW以外的其他地方,则我的布局可能会损坏.

I've managed to make it work, but I'm having to do something kludgy. Specifically, I haven't found a good way to figure out how big (in pixels) a bit of text is, so I have to guess at sizing the TextCtrls in order to just fit the biggest (4 letter) code. My concern is that if the size of the text was to change, or the application was ported to something other than MSW, that my layout might break.

我发现的解决方案是创建一个StaticText对象,用4个大字母填充它,获取其大小,然后对它进行.Destroy().这行得通,但实际上似乎是一个笨拙的解决方案.有没有人有一种更直接的方法来确定TextCtrl中任意文本字符串的大小?我查看了文档,却找不到任何东西,也没有看到任何示例可以完全按照我的意图进行操作.

The solution I found was to create a StaticText object, fill it with 4 large letters, get its size, and then .Destroy() it. This works, but it really seems like a klunky solution. Does anyone have a more direct method for figuring out just how big an arbitrary text string will be in a TextCtrl? I've looked in the docs and haven't been able to find anything, and I haven't seen any examples that do precisely what I'm trying to do.

下面是一些代码示例(显示了测试方法):

A little code sample (showing the test method) follows:

    # This creates and then immediately destroys a static text control
    # in order to learn how big four characters are in the current font.
    testst = wx.StaticText(self, id = wx.ID_ANY, label = "XXXX")
    self.fourlettertextsize = testst.GetClientSize() + (4,4)
    testst.Destroy()

(+(4,4)部分是在控件中添加一些空间以容纳光标,并在TextCtrl的工作区中添加一些边框;这是我宁愿不直接做的另一件事)

(The + (4,4) part is to add a little more space in the control to accommodate the cursor and a little border in the client area of the TextCtrl; this is another thing I'd rather not be doing directly.)

推荐答案

使用面部,大小等创建一个wx.Font实例;创建一个wx.DC;然后在其上调用dc.GetTextExtent("a text string")以获取显示该字符串所需的宽度和高度.在网格中相应地设置行高和列宽.

Create a wx.Font instance with the face, size, etc.; create a wx.DC; then call dc.GetTextExtent("a text string") on that to get the width and height needed to display that string. Set your row height and column width in the grid accordingly.

类似的东西:

font = wx.Font(...)
dc = wx.DC()
dc.SetFont(font)
w,h = dc.GetTextExtent("test string")

这篇关于在wxPython中查找文本大小的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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