pythontkintertkinter-buttontkinter-layout

Move buttons to East with grid method


So a little stylistic thing I want to do is move some buttons to the east side of the window while having them all on the same row.

Sounds easy enough and the grid method has a sticky parameter that should make this easy to do, right? No.

This is the basic code

from tkinter import *

window = Tk()
window.geometry("200x200")

btn1 = Button(window, text="btn1")
btn1.grid(row=0, column=0, sticky="E")
btn2 = Button(window, text="btn2")
btn2.grid(row=0, column=1, sticky="E")

window.mainloop()

What I want is:

-------------------------
|         ------ ------ |
|         |btn1| |btn2| |
|         ------ ------ |
-------------------------

What I'm getting is:

-------------------------
| ------ ------         |
| |btn1| |btn2|         |
| ------ ------         |
-------------------------

Which is sticking to the West even though I specified East

What am I doing wrong? How can I get the result I want?


Solution

  • Give column 0 some weigth. It will force column 1 and 2 to right.

    from tkinter import *
    
    window = Tk()
    window.geometry("200x200")
    window.columnconfigure(0, weight=3)
    btn1 = Button(window, text="btn1")
    btn1.grid(row=0, column=1)
    btn2 = Button(window, text="btn2")
    btn2.grid(row=0, column=2)
    
    window.mainloop()
    

    Another way to do this is using pack() and Frame()

    from tkinter import *
    window = Tk()
    window.geometry("200x200")
    cbframe = Frame(window)
    btn1 = Button(cbframe, text="btn1")
    btn1.pack(side="right", fill=None, expand=False)
    btn2 = Button(cbframe, text="btn2")
    btn2.pack(side="right", fill=None, expand=False)
    
    cbframe.pack(side="top", fill="both", expand=False)
    window.mainloop()