Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python 2.7 - Text alignment issue in 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

image

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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".

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 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.

For example:

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

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")

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...