问题描述
限时送ChatGPT账号..我想要一个 Python 中的消息框,它显示连接的字符串文本.我希望文本左对齐,但事实并非如此.我尝试了 ljust()
和 {:<14}
等,但它仍然没有对齐.
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.
好像是这样:
代码如下,
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)
扇区 ID 部分没问题,但扇区名称未左对齐.有什么想法吗?
Sector id part is fine but sector name is not left aligned. Any idea?
推荐答案
你的代码没有问题.
问题在于您使用的是非单位长度non-monospace
字体,其中字符不占用相同的空间.
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.
这可以通过更改为 monospace
字体来解决,例如 consolas
This can be fixed by changing to a monospace
font like consolas
import tkFont
my_font = tkFont.Font(family='Consolas', size=15, weight='bold')
# then plug in the font to your widget ...
所以在你的代码中它会是这样的
so in your code it would be something like
label_id = tkinter.Label(f, anchor=tkinter.W, text=sector_id, font=('Consolas', 15))
label_name = tkinter.Label(f, anchor=tkinter.W, text=sector_name, font=('Consolas', 15))
这篇关于Tkinter 中的字符串对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论