0

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

SiHa
  • 7,830
  • 13
  • 34
  • 43
Dev Aggarwal
  • 7,627
  • 3
  • 38
  • 50
  • 1
    You need to use a fixed width font in the listbox. – Bryan Oakley Oct 23 '16 at 18:03
  • i dont think i changed the font. you can clearly see that they're all the same size in the console output.. – Dev Aggarwal Oct 24 '16 at 17:20
  • If you didn't change the font, then you probably have a variable-width font. I'm pretty sure tkinter defaults to variable-width fonts. You can clearly see that the two windows use different fonts (look at the zero character, for example). – Bryan Oakley Oct 24 '16 at 17:28
  • can you please advice a fix?? AFAIK, i didnt change any fonts in my entire code for this program. HECK, i dont even know how to do that. – Dev Aggarwal Oct 25 '16 at 07:12

1 Answers1

1

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • i know comments are not for saying thanks. But i cant upvote (repo <15) so THANKS! – Dev Aggarwal Oct 25 '16 at 17:27
  • If Bryan's answer did solve your issue, you should mark it as "accepted" with the green checkmark, so that other users may find the correct answer whenever they find the same type of question ;) – Victor Domingos May 04 '17 at 11:36