Tkinter中Canvas图片切换异常:点击按钮后画布空白
Hey there, let's break down why your image disappears when you click the button, and how to fix it quickly!
The Root Cause
When you create photo2 inside the change_image() function, it's a local variable. As soon as the function finishes running, Python's garbage collector cleans up this local variable—since there are no other references to it. Tkinter relies on having an active reference to the image object to display it, so once photo2 is gone, the canvas goes blank.
When you moved the photo2 code into the main program, it became a global variable, which doesn't get cleaned up while your app is running—that's why the image showed up correctly there.
Simple Fixes
Here are a couple of easy ways to keep the image reference alive:
1. Use a Global Variable
Declare photo2 as a global variable inside your function so it doesn't get discarded after the function runs:
def change_image(): global photo2 # Mark this variable as global photo2 = tk.PhotoImage(file="I.png") canvas.itemconfig(myimg, image=photo2) # Rest of your code remains the same root = tk.Tk() root.title('Image show case') canvas = tk.Canvas(root, width=300, height=200, bg='white') canvas.pack(expand=tk.YES, fill=tk.BOTH) photo = tk.PhotoImage(file="V.png", master=root) myimg = canvas.create_image(0,0, image=photo, anchor=tk.NW) num1Entry = tk.Entry(root) num1Entry.pack(side=tk.LEFT) Button = tk.Button(root, text='Clickme', command=change_image) Button.pack(side=tk.LEFT ) root.mainloop() # Don't forget to add this to start the app!
2. Bind the Image to a Persistent Object
Instead of using a global variable, you can attach the image object to your canvas (or root window) so it stays referenced as long as the canvas exists:
def change_image(): photo2 = tk.PhotoImage(file="I.png") canvas.photo2 = photo2 # Bind the image to the canvas object canvas.itemconfig(myimg, image=photo2) # Rest of your code stays identical to the fixed version above
Bonus Tip
If you plan to switch between multiple images dynamically, you can store all your image objects in a list (declared globally or attached to the canvas) to keep their references alive:
# In the main program images = [] def change_image(): photo2 = tk.PhotoImage(file="I.png") images.append(photo2) canvas.itemconfig(myimg, image=photo2)
This is a super common gotcha with Tkinter's PhotoImage—just remember to keep a reference to the image object somewhere that won't get garbage collected!
内容的提问来源于stack exchange,提问作者Raven Cheuk

