[pygtk] Getting string with in pixels

John Finlay finlay at moeraki.com
Sat Feb 14 17:34:47 WST 2009


vladovi at atlas.cz wrote:
> Walter Leibbrandt <walter at translate.org.za> napsal(a) :
>
>   
>> Hi,
>>
>> Vladimír Jícha wrote:
>>     
>>> Hello,
>>>
>>> I'm trying to get width of a text string. I found a FAQ 4.15 
>>> (http://faq.pygtk.org/index.py?req=show&file=faq04.015.htp) which has a 
>>> solution for this. But unfortunately it doesn't work. If I use "font = 
>>> widget.get_style().font", I get following error message: AttributeError: 
>>> 'gtk.Style' has no attribute 'font'.
>>>
>>> Is the FAQ outdated? What syntax should I use?
>>>
>>> Thank yo
>>>       
>> Try widget.get_style().get_font().
>>
>>     
>
> Thanks for your answer. Unfortunately it doens't work correctly for me. I have following 2 problems:
> 1) I get a DeprecationWarning for the line.
> 2) No matter what fond and size I use, I get the same width.
>
> Sample code:
>
>         label = gtk.Label()
>         name_font = pango.FontDescription("Times 10")
>         label.modify_font(name_font)
>         font = label.get_style().get_font()
>         label2 = gtk.Label()
>         name_font2 = pango.FontDescription("Sans Bold 12")
>         label2.modify_font(name_font2)
>         font2 = label2.get_style().get_font()
>         print font.width("string"), font2.width("string")
>
> I always get the same numbers. Is something wrong in my code?
>   
You should use the PangoLayout to retrieve the pixel size of the text. Use:

label.get_layout().get_pixel_size()

to get the width and height of the label string in pixels.

John


More information about the pygtk mailing list