Search code examples
pythonuser-interfacetkinteruser-experience

tkinter: How do I make these boxes fit to the left and be in straight line


As you can see my boxes are not in straight line. I would like to make them be in straight line and more to the left. my code:

has_lower_box = tk.Checkbutton(root, text="lower chars", variable=has_lower_value)
has_lower_box.grid(row=0, column=1)
has_upper_box = tk.Checkbutton(root, text="upper chars", variable=has_upper_value)
has_upper_box.grid(row=1, column=1)
has_upper_box = tk.Checkbutton(root, text="special chars", variable=has_special_value)
has_upper_box.grid(row=2, column=1)

checkboxes


Solution

  • Here's how to line them up using the sticky= Tkinter Grid Geometry Manager option. I set it to sticky=W for West, which of course means the left side.

    import tkinter as tk
    from tkinter.constants import *
    
    root = tk.Tk()
    
    has_lower_value = tk.BooleanVar()
    has_upper_value = tk.BooleanVar()
    has_special_value = tk.BooleanVar()
    
    has_lower_box = tk.Checkbutton(root, text="lower chars", variable=has_lower_value)
    has_lower_box.grid(row=0, column=1, sticky=W)
    has_upper_box = tk.Checkbutton(root, text="upper chars", variable=has_upper_value)
    has_upper_box.grid(row=1, column=1, sticky=W)
    has_upper_box = tk.Checkbutton(root, text="special chars", variable=has_special_value)
    has_upper_box.grid(row=2, column=1, sticky=W)
    
    root.mainloop()
    

    Here's an enlarged screenshot showing the results:

    enlarged screenshot