Python tkinter窗口如何检测键盘按键触发背景图片切换
按键切换背景实现方案
核心改动共3处:
- 提前预加载两张背景图,保留全局引用避免被Python垃圾回收销毁,导致图片显示空白
- 给主窗口绑定任意键盘输入的触发事件
- 编写事件回调函数,直接修改背景标签的图片属性即可完成替换
修改后完整可运行代码
from tkinter import * root = Tk() root.title('FAS') root.geometry("600x650") #root.attributes('-alpha', 0.5) root.wm_attributes("-topmost", True) root.lift() root.wm_attributes("-transparentcolor", "grey") # 预加载两张背景图片,必须保留全局引用否则会被GC回收 bg_default = PhotoImage(file="3MtoCW.png") bg_new = PhotoImage(file="3MswCW.png") # 切换背景的回调函数 def switch_background(event): my_label.config(image=bg_new) # 绑定任意键盘按键事件,窗口获得焦点时触发 root.bind("<Key>", switch_background) #this is to make the background image transparents red_frame = Frame(root, width=600, height=650, bg='grey') red_frame.place(x=0, y=0) my_label = Label(root, image=bg_default, bg='grey') my_label.place(x=0, y=0) root.mainloop()
补充说明
- 如需实现按一次切换一次、两张图来回更换的效果,可以增加状态变量标记当前显示的图片,回调中判断后切换即可,参考代码:
# 全局状态变量,标记当前是否显示默认图 is_show_default = True def switch_background(event): global is_show_default # 切换显示的图片 target_img = bg_new if is_show_default else bg_default my_label.config(image=target_img) # 反转状态标记 is_show_default = not is_show_default
- 两张图片的底色必须和代码里的
grey完全匹配,否则透明色逻辑会失效,出现灰色不透明区块 - 如果出现按键无响应的情况,可以将绑定语句改为
root.bind_all("<Key>", switch_background),只要程序在前台运行就能接收按键事件 - 如需指定特定按键触发而非任意键,只需将绑定语句里的
<Key>替换为对应按键标识符即可,比如按空格触发用<space>,按回车触发用<Return>
内容的提问来源于stack exchange,提问作者Aynez_
相关产品推荐
相关产品推荐

