79758739

Date: 2025-09-08 10:08:40
Score: 2.5
Natty:
Report link

Thanks SBKubic,

Optimized schemes (such as functions) no longer inherit the actual dict of local variables but instead receive a copy when calling locals(). Mutating that dict does not affect the actual local namespace; therefore, setting locals()[name] = value does not create the variable in the function, and subsequent calls to locals()[name] will still cause it to be missing, raising a KeyError when accessing it. This is part of the new semantics for locals() introduced in Python 3.13 (PEP 667).

In my example, since, as I mentioned, the three lines are in a loop, the Tkinter text widget only keeps visible the images that still have a live reference in Python. In my loop, I'm assigning each new PhotoImage to the same global variable locals_variable, so previous references are lost and removed by Python's garbage collector. That's why only the last inserted image remains.

To keep all PhotoImage instances alive, for example, store them in a global list or as a widget attribute:

imagenes = []

def add_image():

    img = PhotoImage(file='../Figuras_Ayuda/Fig10.png')
    imagenes.append(img)
    my_text.image_create(END,image=img)
Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Blacklisted phrase (2): Ayuda
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: user28238345