Search code examples
pythontkintergrid-layout

Python - Widget alignment when using multiple frames


I'm facing some trouble aligning tkinter widgets when located in different frames, as shown in attached picture

I have 3 frames: main_frame - colored in blue, containing 3 subframes: buttons_frame,timers_frame,switches_frame, which all centered to main_frame, one on top of other.

Design requires: all widgets in all subframes will be centered inside its frame. As shown in attached pic, and code - middle sub-frame, timers_frame is streched OK to max size using tk.E+tk.w, BUT widgets inside positioned at row=0, column=0 and not aligning to center of streched frame. Using tk.E+tk.W didn't solve it.

Solving it without using sub-frames, works OK.

Relevant portion of code:

class CoreButton(ttk.Frame):

    def __init__(self, master, nickname='CoreBut.inc', hw_in=[], hw_out=[], ip_in='', \
                 ip_out='', sched_vector=[], num_buts=1):

        ttk.Frame.__init__(self, master)

        # Styles
        self.style = ttk.Style()
        self.style.configure("Azure.TFrame", background='azure4')
        self.style.configure("Blue.TFrame", background='blue')
        self.style.configure("Blue2.TFrame", background='light steel blue')
        self.style.configure("Red.TButton", foreground='red')

        # Frames
        # Buttons&Indicators
        py, px = 4, 4
        self.main_frame = ttk.Frame(self, style="Blue2.TFrame", relief=tk.RIDGE)
        self.main_frame.grid()

        self.buttons_frame = ttk.Frame(self.main_frame, relief=tk.RIDGE, style="Azure.TFrame")
        self.buttons_frame.grid(row=0, column=0, pady=py, padx=px)

        # Counters
        self.timers_frame = ttk.Frame(self.main_frame, relief=tk.RIDGE, border=5, style="Azure.TFrame")
        self.timers_frame.grid(row=1, column=0, pady=py, padx=px, sticky=tk.E+tk.W)
        # Extra GUI
        self.switches_frame = ttk.Frame(self.main_frame, relief=tk.RIDGE, border=5, style="Azure.TFrame")
        self.switches_frame.grid(row=2, column=0, pady=py)



        # Run Gui
        # self.build_gui()
        self.extras_gui()

    def extras_gui(self):


        ck1 = tk.Checkbutton(self.switches_frame, text='On/Off', variable=self.on_off_var, \
                             indicatoron=1, command=self.disable_but)
        ck1.grid(row=0, column=0)

        ck2 = tk.Checkbutton(self.switches_frame, text='Schedule', variable=self.enable_disable_sched_var, \
                             indicatoron=1,
                             command=lambda: self.disable_sched_task(s=self.enable_disable_sched_var.get()))
        ck2.grid(row=1, column=0)

Solution

  • You have to give the column your timers are in weight!

    self.timers_frame.columnconfigure(0, weight=1)
    

    Otherwise the column has exactly the width of your timers and not the width of your timers_frame.