Search code examples
pythontkinteranchorpacking

In Tk with Python, how do I specify a Frame or Canvas to resize with my window?


I'm totally new to Tk and the Packing concept, so bear with me. Here is my code:

from Tkinter import *

class frm_main:

    def __init__(self, parent):
        self.frame = Frame(parent, bg="green") #green for testing
        self.frame.pack(fill="both")

        self.canvas = Canvas(self.frame, bg="black", width=1000, height=700)
        self.canvas.pack(fill="both")

root = Tk()
main_frm = frm_main(root)
root.mainloop()

I have tried several different options and tests and it looks like the frame and the canvas are each anchored and expanding in the x direction, but resizing in the y direction leaves a bunch of empty space.

How do I get the Frame to anchor to all sides of my window and then the canvas to anchor to all sides of my frame? Should I even use a Frame?


Solution

  • Set expand = 1 in the calls to pack() to make the widgets adjust when their containers are resized.

    self.frame.pack(fill = "both", expand = 1)
    ...
    self.canvas.pack(fill = "both", expand = 1)
    

    You can use a frame to group a set of widgets or add an extra border, but in this example there is no need for the frame.