Search code examples
pythonpython-3.xtkintertkinter-layouttkinter-button

In Tkinter, How does padx differ when used as argument within a widget and an argument in the grid function?


from tkinter import *
window = Tk()

x = Button(text="a", padx=20)
y = Button(text="aaaaa", padx=20)

x.grid(padx=20)
y.grid(padx=20)


window.mainloop()

Despite having the same padding values, x and y buttons have the same size and are displayed at different distances from the left border of the window. In addition, What unit are the padx values?


Solution

  • Look at this:

    The grid(padx=20) adds 20 pixels to the left and right of the button. The padx=20 that is inside the constructor adds 20 pixels to the left and right of the text inside the button. As you aren't allowing the top button to expand, it centres itself in the middle of the window. As that button is smaller (because it has less text inside it) it looks like there is more free space to the left/right of the button

    If you allow both buttons to expand like this:

    x.grid(padx=20, sticky="news")
    y.grid(padx=20, sticky="news")
    

    You will see that the top button becomes the same size as the bottom one.