Search code examples
python-3.xpysimpleguitabulate

How to make tabulate package work with PySimpleGUI? Output is not aligned correctly


I am trying to use tabulate in order to produce a nice table output. It works fine when using print, but when I update a Text-element with the exact same string, it's not vertically aligned.

I get this ugly result in PySimpleGUI:

Innskudd/uttak      Beløp i kr
---------------- ----------
Innskudd                4000
Uttak                 3000
Innskudd               10000

When I copy the textresult from PySimpleGUI and paste it somewhere else, it gives the result:

Innskudd/uttak      Beløp i kr
----------------  ------------
Innskudd                  4000
Uttak                     3000
Innskudd                 10000

Which is the result I want.

Here is MWE of my code:

import PySimpleGUI as sg
from tabulate import tabulate

def txt_out(txt):
    window["-txtUt-"].update(txt)

def se_bevegelser():
    headings = ["Innskudd/uttak", "Beløp i kr"]
    data = [["Innskudd", 4000], ["Uttak", 3000], ["Innskudd", 10000]]
        
    my_table = tabulate(data, headings)
    txt_out(my_table)  # Looks bad
    print(my_table)  # Looks correct

sg.set_options(font="Default 20")

layout = [[sg.Button("Se siste bevegelser", key='-btnSeBevegelser-')],
          [sg.Text("",size=(40,5), key="-txtUt-")],
          [sg.Button("Avslutt")]
          ]

window = sg.Window("Min Minibank", layout)

while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, "Avslutt"):
        break
    elif event == "-btnSeBevegelser-":
        se_bevegelser()
    
window.close()

I've tried to figure out what the default font of python-output is, but I haven't figured that out. I've also tried the Multiline element instead of Text, but it made no difference.

Now I'm asking the professional community out here for help.


Solution

  • The answer, provided by Jason Yang, is to use a mono-space font, like ("Courier New", 20).

    Hence I changed sg.set_options(font="Default 20") to sg.set_options(font=("Courier New", 20)).