如何解决如何在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")
#background image
bg = PhotoImage(file="3MtoCW.png")
#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,bg='grey')
my_label.place(x=0,y=0)
root.mainloop()
我希望当我在 tkinter 窗口中按下一个键时,原始背景图像“3MtoCW.png”将交换为一个名为“3MswCW.png”的新背景图像 我该怎么做?
解决方法
您需要创建一个函数来更改按键上的标签配置并将此函数绑定到事件
下面应该可以解决问题
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")
bg_images = ["3MtoCW.jpg","3MswCW.jpg"]
idx = 0
# background image
bg = PhotoImage(file="3MtoCW.png")
red_frame = Frame(root,width=600,height=650,bg='red')
red_frame.place(x=0,y=0)
my_label = Label(root,image=bg,bg='grey')
my_label.place(x=0,y=0)
def keypress(e):
print("called")
global idx
idx = (idx + 1) % 2
my_label.config(image=PhotoImage(file=bg_images[idx]))
red_frame.bind("<KeyPress>",keypress)
red_frame.pack()
red_frame.focus_set()
root.mainloop()
,
您想将一个事件绑定到 root。这是您可以“查找”的事件列表 https://www.python-course.eu/tkinter_events_binds.php
bg = PhotoImage(file="3MtoCW.png")
root.bind('<KeyPress>',lambda: bg.configure(file="3MswCW.png")
或者不使用 lambda,您可以在新函数中执行此操作。绑定事件时一定要省略括号,否则它会调用函数而不是指向它。
def changeimage(event=None):
bg.configure(file="3MswCW.png")
root.bind('<KeyPress>',changeimage)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。