0
votes

I want to make three buttons in a row, but the width of the widgets isnt the same factor as the tkinter window (wanted to have each button 1/3 width of the tkinter windows width(400px).

Here is the code:

from tkinter import *

window = Tk()
window.geometry("400x400")
window.update()
print(window.winfo_width())
button = Button(window, width=window.winfo_width() // 3)
button.grid(row=0, column=0)
button = Button(window, width=window.winfo_width() // 3)
button.grid(row=0, column=1)
button = Button(window, width=window.winfo_width() // 3)
button.grid(row=0, column=2)

window.mainloop()

How can i solve this? Thanks in advance.

Edit:

Thanks everyone i have figured it out. If someone else has the same problem, this site might also help.

2
Don't use width= use .grid(..., sticky='ew') and allow the Columns to grow using window.grid(0, weight=1). Do so for all Column. - stovfl

2 Answers

0
votes

Unless you'ver specified images, the width of a button is specified in the number of characters, not the number of pixels.

There are better ways to make sure each button is 1/3 of the window. Since you're using grid, you can force the columns to be equal in size using the uniform option. Just set it to the same string for every column, and give every column a non-zero weight so that they grow equally if there's extra space.

Note: I find it much easier to solve layout problems when all of the layout code for a window is grouped together instead of interleaved with other code, so that's how I've structured this example.

from tkinter import *

window = Tk()
window.geometry("400x400")
window.update()
print(window.winfo_width())

window.grid_columnconfigure((0,1,2), uniform="equal", weight=1)

button1 = Button(window)
button2 = Button(window)
button3 = Button(window)

button1.grid(row=0, column=0, sticky="ew")
button2.grid(row=0, column=1, sticky="ew")
button3.grid(row=0, column=2, sticky="ew")

window.mainloop()
0
votes

Specifying just a sticky option in the button won't work.

Using the grid_columnconfigure method from tkinter with a non-zero weight option will configure the columns, letting the button grow or shrink with the window when horizontally stretched.



    from tkinter import *
    window = Tk()
    window.geometry("400x400")
    btn1 = Button(text='button 1')
    btn2 = Button(text='button 2')
    btn3 = Button(text='button 3')

    btn1.grid(row=0, column=0, sticky='ew')
    btn2.grid(row=0, column=1, sticky='ew')
    btn3.grid(row=0, column=2, sticky='ew')

    window.grid_columnconfigure([0,1,2],weight=1)
    window.mainloop()