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
相关产品推荐
相关产品推荐

