Monday, October 18, 2010

PyGTK - How to get text size in pixels

When you search internet for simplest way how to get size of text in pixels in PyGTK you will end up with many tutorials, but still you will not know how to do it. Probably best knowledge base I have found is faq.pygtk.org.

You need only two commands, if you have already any gtk.Widget:

pango = widget.create_pango_layout('your text')

(text_width, text_height) = pango.get_pixel_size()


You should take into account that text_width and text_height are not constant for your pygtk application during runtime, because user can change system theme, and your application should react accordingly. This type of change is propagated to your application through pango.Layout.context_changed() event.