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

如何在Tkinter的if语句中使用按钮的image属性

Tkinter按钮图片属性判断方案
  • 直接通过按钮的cget("image")获取的是图片的名称字符串,无法直接和PhotoImage对象(比如photo2)比较,因为两者类型不同。
  • 推荐两种可行方案:

方案1:维护状态变量记录当前图片

初始化时定义变量记录当前使用的图片,每次切换图片同步更新该变量,后续判断直接使用这个变量即可:

import tkinter as tk

root = tk.Tk()
photo1 = tk.PhotoImage(file="img1.png")
photo2 = tk.PhotoImage(file="img2.png")
current_photo = photo1

def switch_image():
    global current_photo
    if current_photo == photo1:
        photobutton.config(image=photo2)
        current_photo = photo2
        # 此处添加当前为photo2时的执行代码
    else:
        photobutton.config(image=photo1)
        current_photo = photo1

photobutton = tk.Button(root, image=current_photo, command=switch_image)
photobutton.pack()
root.mainloop()

方案2:比较图片对象的名称属性

每个PhotoImage对象都自带name属性,按钮cget("image")返回的就是这个名称字符串,通过对比名称可以判断当前图片:

def check_current_image():
    if photobutton.cget("image") == photo2.name:
        # 执行你需要的代码逻辑
        print("当前显示的是photo2")
  • 注意:hasattr()方法不适用此场景,因为按钮的image属性始终存在(未设置时为空字符串),无法用来判断当前使用的具体图片。

内容的提问来源于stack exchange,提问作者user21300075

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:02:44