简体   繁体   English

如何自动调整文本大小以适合固定大小的PyGTK标签?

[英]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.

相关问题 如何在 Processing 中编码固定数量的半随机间隔的行并且仍然适合固定大小的图像? - How do I code, in Processing, a fixed number of lines that are semi-randomly spaced apart and still fit into a fixed-size image? PyGTK:如何使图像自动缩放以适合其父小部件? - PyGTK: How do I make an image automatically scale to fit its parent widget? 如何调整图像大小以适合标签大小? (Python) - how to resize an image to fit the label size? (python) 如何获得pygtk窗口的大小? - How do I get the size of a pygtk window? 当我用鼠标调整 kivy 中的 window 大小时,如何自动调整小部件(按钮/标签)的文本大小 - How to resize automatically the text from a widget(button/label) when i resize the window in kivy with the mouse 删除numpy固定大小数组中的固定大小约束 - Remove the fixed-size constraint in numpy fixed-size array 如何在Cython中初始化固定大小的整数numpy数组? - how to initialize fixed-size integer numpy arrays in Cython? 如何在 Python 中创建一个固定大小的字节变量 - How to make a fixed-size byte variable in Python 如何使 label 文本轮廓并适合 label 的大小 - How to make label text outlined AND fit the size of the label 如何将函数参数限制为固定大小的数组? - How to limit function parameter as array of fixed-size?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM