You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

保留报错代码行时图片可正常切换,删除该行后图片无法显示的问题求助

保留报错代码行时图片可正常切换,删除该行后图片无法显示的问题求助

大家好,我碰到了一个百思不得其解的tkinter图片显示问题,想请教一下各位:

我编写了一段代码,实现鼠标悬停在不同按钮上时切换显示对应的区域图片。但代码里的第27行photo = ImageTk.PhotoImage(img)明明会报错(提示'PhotoImage' object has no attribute '...',本质是不能把已经是PhotoImage类型的对象再传入PhotoImage构造函数),可奇怪的是,就算触发这个错误,程序依然能正常切换图片;可一旦我把这行错误代码删掉,鼠标悬停时图片就变成空白区域,完全不显示了。

我实在想不通这是为什么——明明这行代码本身就是错误的,为什么删掉它反而功能失效了?以下是我的完整代码:

import tkinter as tk
from PIL import Image, ImageTk
import string # string.ascii_lowercase = "abcdefghijklmnopqrstuvwxyz"

def on_enter(event):
    global image_label
    btn=str(event.widget)

    match btn:
        case ".1":
            img = Image.open("District_1b.png")
        case ".2":
            img = Image.open("District_2b.png")
        case ".3":
            img = Image.open("District_3b.png")
        case ".4":
            img = Image.open("District_4b.png")            
        case ".5":
            img = Image.open("District_5b.png")            
        case ".6":
            img = Image.open("District_6b.png")            
        case ".7":
            img = Image.open("Districtsb.png")

    img = ImageTk.PhotoImage(img)
    image_label.configure(image=img)
    photo = ImageTk.PhotoImage(img)
    
def on_leave(event):
    global image_label
    #image_label.destroy()

root = tk.Tk()

button1 = tk.Button(root, text="District I", name="1")
button1.grid(row=0,column=0)
button2 = tk.Button(root, text="District II", name="2")
button2.grid(row=0,column=1)
button3 = tk.Button(root, text="District III", name="3")
button3.grid(row=0,column=2)
button4 = tk.Button(root, text="District IV", name="4")
button4.grid(row=0,column=3)
button5 = tk.Button(root, text="District V", name="5")
button5.grid(row=0,column=4)
button6 = tk.Button(root, text="District VI", name="6")
button6.grid(row=0,column=5)
button7 = tk.Button(root, text="All District's", name="7")
button7.grid(row=0,column=6)

img = Image.open("Screenshot 2024-12-13 144137.png")
img = ImageTk.PhotoImage(img)
image_label = tk.Label(root,width=1400, image=img)
image_label.grid(row=1,column=0, columnspan=8)

button1.bind("<Enter>", on_enter)
button1.bind("<Leave>", on_leave)
button2.bind("<Enter>", on_enter)
button2.bind("<Leave>", on_leave)
button3.bind("<Enter>", on_enter)
button3.bind("<Leave>", on_leave)
button4.bind("<Enter>", on_enter)
button4.bind("<Leave>", on_leave)
button5.bind("<Enter>", on_enter)
button5.bind("<Leave>", on_leave)
button6.bind("<Enter>", on_enter)
button6.bind("<Leave>", on_leave)
button7.bind("<Enter>", on_enter)
button7.bind("<Leave>", on_leave)

root.mainloop()

我已经明确知道报错是因为重复转换PhotoImage对象,但就是搞不懂为什么错误代码存在时功能反而正常,删掉就失效。希望有人能帮我解释这个现象,并给出正确的代码写法。

备注:内容来源于stack exchange,提问作者Rjtaylor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 08:28:01