I want a message box in Python which shows the concatenated string text.
I want the text is left aligned but it doesn't.
I tried ljust()
and {:<14}
etc. But it still not aligned.
It seems like this:
The code piece is below,
for todo_item in resp.json()['SectorList']:
sector_id +='Sector Id: {:<14}'.format(todo_item['SectorId']) + '\n'
sector_name += 'Sector Name: {:<40}'.format(todo_item['SectorName']) + '\n'
After the loop I add those texts into my message box.
label_id = tkinter.Label(f, anchor = tkinter.W, text = sector_id)
label_name= tkinter.Label(f,anchor = tkinter.W, text = sector_name)
label_id.grid(row= 2, column = 1, sticky = tkinter.W)
label_name.grid(row= 2, column = 2, sticky = tkinter.W)
Sector id part is fine but sector name is not left aligned. Any idea?
There is no problem with your code.
The problem lies in the fact that you are using non-unit length
non-monospace
font, where the characters do not take up the same amount of space.This can be fixed by changing to a
monospace
font likeconsolas
so in your code it would be something like
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 aInput
or something else later on? Do we now have to add newLabel
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:There are more ways to do this, though. For example by setting a width using
columnconfigure
:The advantage of using
columnconfigure()
is that the minimum width is independent of the column's contents. So if you change theLabel()
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.You need a fixed width font for that approach to work.
For each platform, TkInter provides Standard Fonts, including "TkFixedFont". This should correspond to a decent (and available) fixed width font for the current platform, so the following is a simple and portable way to get a fixed width font: