I had a very difficult time trying to search the web for how to left align text in a GTKLabel in Python. So finally when I figured it out from some C language code, I thought it would benefit others Googling for code snippet to left align a text in GTK Label in Python.
The difficulty arises from the fact that by default the contents are center aligned in GTKLabel. I use Glade to build GUI applications in Python. So below is the code snippet if you want to left algin text in a GTKLabel in Python.
label = Gtk.Label("My Text")
label.set_alignment(0,0)
Code language: Python (python)
Yes, it is as simple as calling the set_alignment method. It takes two argument, one is horizontal alignment and the other is vertical aligment. So for left aligning the text, we are interested in the first argument which is horizontal alignment.
Hence, by passing 0 as the first argument, we make sure that the text in GTK Label is left aligned. If you want some small padding instead of aligning it to complete left, the code could be modified to have some minimum left padding as follows.
label.set_alignment(0.05,0)
Code language: Python (python)
On the other hand, if you want to right align the text in GTK Label, then the code would be as follows.
label.set_alignment(1,0)
The above line will right align the text. As you can guess, the code for the default center aligning of text then would be as follows:
label.set_alignment(0.5,0)
Code language: Python (python)
Similarly you can adjust the second parameter to modify vertical alignment of text to top, middle or bottom of the label.