简体   繁体   中英

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

I have a fixed-size gtk.Label . I would like to automatically resize the text so that it fits 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM