How to align Tkinter Checkbutton left when using sticky="EW"?

340 Views Asked by At

I want to align dynamically created Tkinter Checkbuttons to left while having widgets added by grid with sticky="EW" at the same time. I also want to display a background color. Here is code and example of such case but where widgets are not aligned to left:

from tkinter import *

root = Tk()

row = 0
check_buttons = []
for i in range(10):
    text = str(i)*row
    check = Checkbutton(root, text=text)
    check.grid(row=row, sticky="WE")
    row += 1
    check.config(bg="green")

root.mainloop()

enter image description here

Here is another example where sticky="W" is used instead. Problem is that widget borders are not aligned from the right side.

enter image description here

I need to have these on grid. Anyone have any idea how to align only button and text to left while expanding entire widget at the same time?

2

There are 2 best solutions below

0
On

Edit: Forgotten to add parameter in CheckButton.

You don't needed do this config when on fly. Just added in line 9 bg='green'

from tkinter import *

root = Tk()

row = 0
 
for i in range(10):
    text = str(i)*row
    check = Checkbutton(root, text=text, bg="green", anchor="w")
    check.grid(row=row, sticky="WE")
    row += 1
    
root.mainloop()
0
On

I figured it out. Adding anchor="w" when creating widget fixes issue. Here is full example code and picture (of what I was looking for):

from tkinter import *

root = Tk()

row = 0
check_buttons = []
for i in range(10):
    text = str(i)*row
    check = Checkbutton(root, text=text, anchor="w")
    check.grid(row=row, sticky="WE")
    row += 1
    check.config(bg="green")

root.mainloop()

enter image description here