开发者

How do I automatically resize text to fit a fixed-size PyGTK label?

开发者 https://www.devze.com 2023-02-04 08:49 出处:网络
I have a fixed-size gtk.Label. I would like to automatically resize the text so that it f开发者_如何学Pythonits within the Label. Is there an elegant way to do this with fonts that are not fixed width

I have a fixed-size gtk.Label. I would like to automatically resize the text so that it f开发者_如何学Pythonits within the Label. Is there an elegant way to do this with fonts that are not fixed width?

my_label = gtk.Label()

# Short text segment
my_label.set_text( "Short text segment." )

# Long text segment
### Determine required text size here. ###
my_label.set_text( "This is a really long text segment that I would like to resize."


I didn't have time to test this, but something along these lines ought to do what you want:

size = 12000 # thousandths of a point
temp_label = gtk.Label(my_label.get_text())
while temp_label.get_width() > my_label.get_width():
    size -= 100
    temp_label.set_attributes(pango.Attrlist().insert(pango.AttrSize(size))
my_label = temp_label

This assumes that you're forcing the width of my_label directly. If my_label is getting it's width from something else (like a parent container) then substitute my_label.get_width() for whatever is the maximum width that you desire.

Essentialy this just drops the font size by 1/10th of a point over and over until the text finally fits. Feel free to tweak the size -= 100 to whatever increment you like (the smaller it is the slower but more fine-grained it will be).

Let me know if that's not quite it and I can refine it later.

0

精彩评论

暂无评论...
验证码 换一张
取 消