[Tutor] Tkinter grid manager

Phil phillor9 at gmail.com
Tue Feb 22 19:11:40 EST 2022


I think I've misunderstood the purpose of the grid manager. The pack 
manager does exactly what I have in mind, but I'll continue with my 
question anyway.

Looking at the following abbreviated code, the "on" and "off" buttons 
are always located on row 0 and column 0 no matter what the row and 
column settings are. Adding a third button means that I can now locate a 
button on column 3, which does make sense. Excessive use of padx and 
pady does place the buttons where I'd like them but I don't think that's 
the correct use of the grid manager.

I'd like to locate the "on" and "off" buttons at the bottom right corner 
of the frame and the pack manager does that so I suppose the pack 
manager is the correct choice in this instance. I think the grid manager 
is more suited to placing a label beside a widget rather that the exact 
placement of a widget.

import tkinter as tk


class Root(tk.Tk):
     def __init__(self):
         super().__init__()
         self.title("Template")
         self.geometry("300x200")

         self.frame = tk.Frame(bg='light blue')

         self.frame.grid(row=0, column=0, sticky='nsew')    # I found 
that I had to add these lines so that
         self.grid_rowconfigure(0, weight = 1)    # the frame would fill 
the main window.
         self.grid_columnconfigure(0, weight = 1)                 # 
Could there be a problem here?

         self.create_widgets()

     def create_widgets(self):

         self.on_button = tk.Button(self.frame,
                                   text="On",
                                   command=self.on_on_button_press)

         self.off_button = tk.Button(self.frame,
                                    text="Off",
command=self.on_off_button_press)

         self.on_button.grid(row=5, column=0, padx=10, pady=10) # row 
can be any value, the result is
         self.off_button.grid(row=5, column=1, padx=10, pady=10) # 
always row 0.

         self.another_button = tk.Button(self.frame,
                                    text="another")

         self.another_button.grid(row=8, column=3, padx=0, pady=60)


     def on_on_button_press(self):
         print('on')

     def on_off_button_press(self):
         print('off')

if __name__ == "__main__":
     root = Root()
     root.mainloop()

-- 
Regards,
Phil



More information about the Tutor mailing list