Home > Net >  In Python tkinter, how to shrink the canvas, not the button, when window reduced the size
In Python tkinter, how to shrink the canvas, not the button, when window reduced the size

Time:07-19

The canvas with options fill=BOTH and expand=True can change the size per window resize. If other widget also layouted in the window, it may reduce the size of other widget, not the canvas.

Is there any method to reduce the size of canvas first when the size of window reduced ?

from tkinter import *

def callback(event):
    print(event.width, event.height)

root = Tk()

canvas = Canvas(root, width=360, height=360, bg='green', bd=0, highlightthickness=0)
canvas.pack(fill=BOTH, expand=1)

button = Button(root, text='Button')
button.pack()

canvas.bind('<Configure>', callback)

root.mainloop()

Platform: WIN10, Python 3.8.10, tkinter 8.6.9

Following figure shown that the size of canvas is not changed, but the size of button reduced first, when window size reduced in vertical direction.

enter image description here

CodePudding user response:

Pack order matters. You can pack the button to the bottom side first, then pack the canvas:

from tkinter import *

def callback(event):
    print(event.width, event.height)

root = Tk()

canvas = Canvas(root, width=360, height=360, bg='green', bd=0, highlightthickness=0)
button = Button(root, text='Button')

# pack button to the bottom firstt
button.pack(side=BOTTOM)
# then pack the canvas
canvas.pack(fill=BOTH, expand=1)

canvas.bind('<Configure>', callback)

root.mainloop()
  • Related