列表框中的文本对齐问题 [英] Text alignment issue in Listbox

查看:52
本文介绍了列表框中的文本对齐问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 tk 制作一个小的 GUI 脚本.根据用户输入进行计算后,我生成了一个简单的字符串,我想使用 listbox 打印该字符串,但它遇到了对齐问题.

I'm trying to make a little GUI script using tk. After computation on the basis of user input, I generate a simple string that I want to print using a listbox, but it was suffering from alignment problems.

我尝试同时在控制台中打印输出以检查这是否是格式错误:

I tried printing the output in the console at the same time to check whether this was a formatting error:

for loop :
    string = foo(x)
    listbox.insert(END, string)
    print string

推荐答案

问题是控制台使用的是固定宽度字体,而列表框使用的是可变宽度字体.在可变宽度字体中,像i"(小写 I)和l"(小写 L)这样的字符比像M"和0"这样的字符占用更少的水平空间.

The problem is that the console is using a fixed width font but the listbox is using a variable width font. In a variable width font, characters like "i" (lowercase I) and "l" (lowercase L) take up less horizontal space that characters like "M" and "0".

如果您希望字符在列表框中像在控制台中一样排列,则需要使用固定宽度的字体.您可以通过 font 属性配置列表框使用的字体.

If you want characters to line up in a listbox like they do in the console, you need to use a fixed width font. You can configure the font used by the listbox via the font attribute.

Tkinter 提供了几种默认字体,默认的等宽字体被命名为 "TkFixedFont".此默认字体与其他小部件使用的默认可变宽度字体的垂直高度大致相同.选择的确切字体在不同平台上可能会有所不同,但通常是 courier 的变体.

Tkinter provides several default fonts, the default fixed-width font is named "TkFixedFont". This default font will be approximately the same vertical height as the default variable width font that is used by other widgets. The exact font that is chosen may be different on different platforms, but is typically a variant of courier.

例如:

import Tkinter as tk
root = tk.Tk()
listbox = tk.Listbox(root, font="TkFixedFont")

如果您希望明确说明字体系列和大小,可以将其作为字符串、元组或字体对象提供.例如,选择大小为 18 的 courier 字体可以指定为 font="Courier 18".

If you wish to be explicit about the font family and size, you can provide that as a string, tuple, or as a font object. For example, picking a courier font of size 18 could be specified as font="Courier 18".

listbox = tk.Listbox(root, font="Courier 18")

有关字体的更多信息,请参阅 关于字体、颜色和图像的 TkDocs 教程以及 effbot 上的小部件样式 部分.

For more information on fonts, see the TkDocs tutorial on fonts, colors and images and the section Widget Styling on effbot.

这篇关于列表框中的文本对齐问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆