Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Any way to do this?

>Solution :

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)

Eventullay it may need sticky='w' to allign it to west side of cell

label.grid(column=0, row=0, columnspan=3, sticky='w')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading