Search code examples
pythontkintertext-alignment

Center text with spaces in button tkinter


Recently, I've been trying to center text inside tkinter (in a button). I've already tried to use button.pack(anchor=tkinter.W), but that didn't work. I want it to be perfectly aligned like in terminal, but I keep on getting this result. I want it to look something like this when I use print in terminal.

Here is my current code:

from tkinter import *
import tkinter
root=Tk()

button=Button(root,text="""
        |---------|
        |         |
        |         0
        |        /|\\
        |        / \\
        |
        |
        |
    """)
button.pack(anchor=tkinter.W)

root.mainloop()

Solution

  • You need to use a mono-spaced font and set justify='left':

    button=Button(root,text=r"""
            |---------|
            |         |
            |         0
            |        /|\
            |        / \
            |
            |
            |
        """, justify='left', font='TkFixedFont')
    

    Result:

    enter image description here