python 如何以像素为单位获取字符串的宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2455255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the width of a string in pixels?
提问by MA1
I am using wxPython's HyperTreeList and I want to set the column width exactly equal to length of the largest string in it.
我正在使用 wxPython 的 HyperTreeList 并且我想将列宽设置为完全等于其中最大字符串的长度。
To accomplish that, I'd like to to convert a python string size into pixels.
为此,我想将 python 字符串大小转换为像素。
For Example: If we have a string like
例如:如果我们有一个像
str = "python"
len(str) = 6
How could I convert the above string length/size into pixels?
如何将上述字符串长度/大小转换为像素?
Is there another way?
还有其他方法吗?
回答by Esteban Küber
You'll have to do somethinglike(see the documentation of wxWidgetsfor more info)
你必须做的事情一样(见的wxWidgets的文档获取更多信息)
f = window.GetFont()
dc = wx.WindowDC(window)
dc.SetFont(f)
width, height = dc.GetTextExtent("Text to measure")
回答by luc
It depends on how you are printing the text.
这取决于您如何打印文本。
You may be interested by PIL ImageDraw
which has a textsize
method. See http://effbot.org/imagingbook/imagedraw.htm
您可能对PIL ImageDraw
其中有一个textsize
方法感兴趣。见http://effbot.org/imagingbook/imagedraw.htm
Update: This was answering the original question. It may looks a little off-topic after question updates.
更新:这是在回答最初的问题。问题更新后,它可能看起来有点离题。