Python tkinter frame canvas resize Python tkinter frame canvas resize tkinter tkinter

Python tkinter frame canvas resize


No need to reinvent the wheel here. Canvas() is a tkinter widget, and like all tkinter widgets it has to be drawn in the window using a geometry manager. This means that we can manipulate how it appears in the window.

Example program below modified from an example found on this page.

If we use .pack() then we can do something like the below:

from tkinter import *root = Tk()w = Canvas(root, width=200, height=100)w.pack(fill="both", expand=True)w.create_line(0, 0, 200, 100)w.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))w.create_rectangle(50, 25, 150, 75, fill="blue")root.mainloop()

Where the combination of fill="both" and expand=True tells the widget to eat up all the extra space it's given in the window and expand to fill it.

If we're using .grid() then we have to do something slightly different:

from tkinter import *root = Tk()root.columnconfigure(0, weight=1)root.rowconfigure(0, weight=1)w = Canvas(root, width=200, height=100)w.grid(sticky=N+S+E+W)w.create_line(0, 0, 200, 100)w.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))w.create_rectangle(50, 25, 150, 75, fill="blue")root.mainloop()

Here we use .rowconfigure() and .columnconfigure to tell row 0 and column 0 (where our canvas is) to have a higher weight than any other row or column, meaning they get given more of the free space in the window than the others (In this case all of it seeing as how no other rows or columns exist), we then need to tell the widget to actually expand with the "cell" it resides in, which we do by specifying sticky=N+S+E+W, which tells the widget to stick to all 4 edges of the cell when they expand, thus expanding the widget.