The Python Oracle

python GTK3 limit label width

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Question
01:55 Accepted answer (Score 7)
02:28 Answer 2 (Score 3)
03:26 Thank you

--

Full question
https://stackoverflow.com/questions/2855...

Answer 1 links:
[here it is]: https://git.gnome.org/browse/gnome-conta...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #gtk #label #width #gtk3

#avk47



ACCEPTED ANSWER

Score 7


So here is a solution (still not the exact pixel width) You can use Gtk.Widget.set_halign to force no horizontal expansion.

Here is the part of the code:

    lbl=gtk.Label(label)
    lbl.set_max_width_chars(5)
    lbl.set_ellipsize(pango.EllipsizeMode.END)
    lbl.set_halign(gtk.Align.CENTER)
    self.add(lbl)

This is what it looks like: screeshot of the window

I hope I did not miss anything this time.




ANSWER 2

Score 3


You do have another option: use a custom GtkContainer implementation that limits its children to exact pixel widths. According to Erick Pérez Castellanos on irc.gimp.net/#gtk+, GNOME Contacts has one; here it is. It's in Vala, but it shouldn't be too hard to wrap your head around alongside some reading of the GtkWidget and GtkContainer (and GtkBin) semantics. Unfortunately I do not know how to create new GObjects in Python, sorry.

If you do use the approach in GNOME Contacts, the custom container (which derives from GtkBin, a convenience for single-child GtkContainers) will hold just your GtkLabel, and you add that to the flowbox item's GtkVBox.

Hopefully that helps.