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

发布于 2024-10-12 05:13:32 字数 349 浏览 1 评论 0原文

我有一个固定大小的 gtk.Label。我想自动调整文本大小,使其适合标签。对于不固定宽度的字体,是否有一种优雅的方法来做到这一点?

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 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."

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一人独醉 2024-10-19 05:13:32

我没有时间对此进行测试,但是沿着这些方向进行的操作应该可以满足您的要求:

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

这假设您直接强制 my_label 的宽度。如果 my_label 从其他东西(例如父容器)获取其宽度,则将 my_label.get_width() 替换为您想要的最大宽度。

本质上,这只是一遍又一遍地将字体大小减小 1/10 点,直到文本最终适合为止。您可以随意将 size -= 100 调整为您喜欢的任何增量(它越小,速度越慢,但粒度会更细)。

如果这不完全是这样,请告诉我,我可以稍后完善它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文