How to prevent tkinter buttons from moving when label text length change?

Question:

I have the following example:

from tkinter import *
number = 0
​
window = Tk()
window.title("Program")
window.geometry('350x250')
​
label = Label(window, text=number)
label.grid(column=0,row=0)
​
def clicked_up():
    global number
    number += 1
    label.config(text=number)
​
def clicked_down():
    global number
    number -= 1
    label.config(text=number)
​
button1 = Button(window, text="Up", command=clicked_up)
button1.grid(column=1, row=1)
button2 = Button(window, text="Down", command=clicked_down)
button2.grid(column=2, row=1)
window.mainloop()

It increments the variable number (or decrements it) based on the button Down or Up presses.

The problem is, that the buttons are moving when the text in the Label (here it’s the result of the increased/decreased variable) is changing length (eg: it’s noticeable once it get bigger than 2 in length, so 10 or 100, or for negative, -100, is also noticeable)

I looked around but didn’t think I found a solution, at least based on the above example.

Any way to do this?

Asked By: Nordine Lotfi

||

Answers:

Label can use width=number_of_chars to define place for new chars

label = Label(window, text=number, width=10)

Or

Label should use columnspan=3 to use 3 columns in grid.

label.grid(column=0, row=0, columnspan=3)

Eventually it may need sticky='w' to align it to west side of cell

label.grid(column=0, row=0, columnspan=3, sticky='w')
Answered By: furas