[英]How do I automatically resize text to fit a fixed-size PyGTK label?
I have a fixed-size gtk.Label
. 我有一个固定大小的
gtk.Label
。 I would like to automatically resize the text so that it fits within the Label. 我想自动调整文本大小,使其适合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. 这假设您直接强制my_label的宽度。 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.
如果my_label从其他东西(如父容器)获取宽度,则将my_label.get_width()替换为您想要的最大宽度。
Essentialy this just drops the font size by 1/10th of a point over and over until the text finally fits. 实际上,这只是将字体大小逐渐减少1/10点,直到文本最终适合。 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).
随意调整大小 - = 100到你喜欢的任何增量(越小越慢,但它将更细粒度)。
Let me know if that's not quite it and I can refine it later. 让我知道,如果不是这样,我可以稍后改进它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.