Tkinter 中的字符串对齐

编程入门 行业动态 更新时间:2024-10-22 21:27:50
本文介绍了Tkinter 中的字符串对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-30 07:34:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391384.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!