Relying on fonts for alignment is bad practice; as mentioned it only works with monospaces fonts, but do you really want to use monospaces fonts in your entire application only for alignment? I sure don't. And what if you want to change a Label
to a Input
or something else later on? Do we now have to add new Label
s just for alignment?
So while changing to a monospaced font "works", a (much) better way would be to use the tools Tk provides us.
For example, you can set the Label()
in the first column to a fixed width:
import tkinter
# Just some random strings of different sizes from my dictionary
names = ['Algol', 'American', 'Americanises', 'Americanising', 'Americanism',
'Argentine', 'Argentinian', 'Ariz', 'Arizona', 'Armstrong']
root = tkinter.Tk()
tkinter.Label(root, text='Lists:', anchor=tkinter.W).grid(row=0, column=0, sticky=tkinter.W)
for i in range(0, 10):
label_id = tkinter.Label(root, width=30, anchor=tkinter.W, text='Sector %s' % i)
label_name = tkinter.Label(root, anchor=tkinter.W, text=names[i])
label_id.grid(row=i+1, column=0, sticky=tkinter.W)
label_name.grid(row=i+1, column=1, sticky=tkinter.W)
root.mainloop()
There are more ways to do this, though. For example by setting a width using columnconfigure
:
import tkinter
# Just some random strings of different sizes from my dictionary
names = ['Algol', 'American', 'Americanises', 'Americanising', 'Americanism',
'Argentine', 'Argentinian', 'Ariz', 'Arizona', 'Armstrong']
root = tkinter.Tk()
root.columnconfigure(0, minsize=150)
tkinter.Label(root, text='Lists:', anchor=tkinter.W).grid(row=0, column=0, sticky=tkinter.W)
for i in range(0, 10):
label_id = tkinter.Label(root, anchor=tkinter.W, text='Sector %s' % i)
label_name = tkinter.Label(root, anchor=tkinter.W, text=names[i])
label_id.grid(row=i+1, column=0, sticky=tkinter.W)
label_name.grid(row=i+1, column=1, sticky=tkinter.W)
root.mainloop()
The advantage of using columnconfigure()
is that the minimum width is independent of the column's contents. So if you change the Label()
to something else later, the layout should still work, and it's probably a bit more obvious that you explicitly want to set a width for this column.