tkinter: Destroying frames with key press leaves container behind

Here is the code:

import tkinter as tk

app = tk.Tk()
container = tk.Frame(app, bg="yellow")

children = []
for i in range(2):
    child = tk.Frame(container, bg="red", height=30, width=30)

def on_key_press(event):
    del children[-1:]
app.bind('<KeyPress>', on_key_press)

#children[0].destroy()     <------- This works and does not leave a yellow square behind.

Pressing any key twice leaves a yellow square behind (from the container, I assume). What is happening?

If I uncomment the commented code above, I don’t see the yellow square when I run the code.


When you remove the second-to-last child, the geometry manager is still in control of the container so the container shrinks. When you delete the last child, the geometry manager no longer is in control of the container so it stays the same size.

If you know you are deleting the last child, you can either explicitly set the width and height to one pixel, or you can pack a 1×1 pixel widget that will force the frame to shrink.