You need to enable JavaScript to run this app. Python tkinter如何实现点击按钮后切换按钮显示图片
优惠活动
大模型
产品
解决方案
定价
更多

Python tkinter如何实现点击按钮后切换按钮显示图片

Tkinter Simon 游戏按钮点击切换灰色/蓝色图片实现方案

现有代码核心问题

  • click()切换函数无效的3个原因:
    • 函数内加载的blue1.png图片是局部变量,会被Python垃圾回收销毁,无法正常渲染
    • 仅加载了图片文件,未执行将图片绑定到目标按钮的操作
    • 按钮的command=click配置被注释,点击按钮不会触发切换逻辑
  • 存在未定义变量btn_img2,运行时会直接触发报错
  • 冗余代码:创建的frame、canvas组件和导入的PIL.Image模块未实际使用

正确实现逻辑

  • 预先加载所有按钮需要的灰色、蓝色素材图,将图片对象挂载到全局变量上,避免被垃圾回收
  • 给按钮绑定点击事件,使用lambda传参避免程序启动时直接执行切换函数,触发后直接修改按钮的image属性为对应蓝色图片对象

修复后可直接运行的代码

import tkinter as tk

HEIGHT = 720
WIDTH = 1280

# 预先加载所有需要的图片,避免被垃圾回收
GRAY_BTN_IMG = tk.PhotoImage(file='gray.png')
BLUE_BTN_IMG = tk.PhotoImage(file='blue1.png')
BG_IMG = tk.PhotoImage(file='img.png')

root = tk.Tk()
root.title("Simon")
root.geometry('1280x720')
root.resizable(False, False)

# 背景图
bg_label = tk.Label(root, image=BG_IMG)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)

# 按钮点击切换逻辑
def switch_to_blue(btn):
    btn.config(image=BLUE_BTN_IMG)

# 按钮1初始化(灰色图)
btn1 = tk.Button(
    root,
    height=63,
    width=63,
    bg='#515151',
    borderwidth=0,
    activebackground='#383B38',
    image=GRAY_BTN_IMG,
    highlightcolor='red',
    command=lambda: switch_to_blue(btn1) # 绑定点击事件,传入当前按钮对象
)
btn1.place(x=730, y=286)

# 其他按钮初始化
btn2 = tk.Button(root,height=3,width=7, bg = '#515151', borderwidth=0, activebackground= '#2969A6')
btn2.place(x=818,y=291)
btn3 = tk.Button(root,height=3,width=7, bg = '#515151', borderwidth=0, activebackground= '#2969A6')
btn3.place(x=903,y=291)

btn4 = tk.Button(root,height=3,width=7, bg = '#515151', borderwidth=0, activebackground= '#2969A6')
btn4.place(x=332,y=368)
btn5 = tk.Button(root,height=3,width=7, bg = '#515151', borderwidth=0, activebackground= '#2969A6')
btn5.place(x=820,y=368)
btn6 = tk.Button(root,height=3,width=7, bg = '#515151', borderwidth=0, activebackground= '#2969A6')
btn6.place(x=482,y=368)

btn7 = tk.Button(root, height=3,width=7, bg = '#515151', borderwidth=0, activebackground= '#2969A6')
btn7.place(x=332,y=445)
btn8 = tk.Button(root,height=3,width=7, bg = '#515151', borderwidth=0, activebackground= '#2969A6')
btn8.place(x=407,y=445)
btn9 = tk.Button(root,height=3,width=7, bg = '#515151', borderwidth=0, activebackground= '#2969A6')
btn9.place(x=482,y=445)

root.mainloop()

注意事项

  • 如果需要点击后再切回灰色,只要在switch_to_blue函数里加判断逻辑,根据当前按钮的图片状态切换即可
  • 素材图需要和代码文件放在同一目录下,否则需要写全图片的绝对路径
  • 如果运行时提示不支持png格式,可安装Pillow库后,用from PIL import ImageTk替换图片加载逻辑:GRAY_BTN_IMG = ImageTk.PhotoImage(Image.open('gray.png'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 21:06:04