Tkinter 解除绑定键事件问题 [英] Tkinter unbinding key event issue

查看:34
本文介绍了Tkinter 解除绑定键事件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,按两次空格键会导致两次连续的哔哔声.我想避免这种情况,而是在发出第一声哔声时禁用该键.我认为解开空格键可能会起作用,但它不会.奇怪的是,似乎只有两声蜂鸣声叠加而不是更多.我猜这个问题的原因可能是 winsound.Beep 是非阻塞的,所以重新绑定几乎是立即发生的.

In the code below, pressing the space bar twice results in two successive beeps. I want to avoid this and instead disable the key while the first beep is happening. I thought unbinding the space key might work, but it doesn't. It's strange that only two beeps seem to stack up rather than more. I'm guessing maybe the cause of the issue is that winsound.Beep is non-blocking so the rebinding occurs almost instantly.

请问有什么关于如何让它工作的建议吗?

Any suggestion on how to get this to work please?

import winsound
from tkinter import *

             
def beep(e):
    frame.unbind("<space>")
    winsound.Beep(440, 1000)
    frame.bind("<space>", beep)


root = Tk()
frame = Frame(root, width=100, height=100)
frame.bind("<space>", beep)
frame.pack()
frame.focus_set()
root.mainloop()

推荐答案

这里有一个解决方案,可以将焦点从小部件上移开,因此不会触发绑定:

Here is a solution that takes the focus away from the widget, so the binding wont get triggered:

import winsound
from tkinter import *

def beep(event):
    dummy.focus_set() #setting focus to dummy
    winsound.Beep(440, 1000) #playing it 
    root.after(1000,frame.focus_set) #setting focus back after playing for 1000 ms

root = Tk()

dummy = Label() #making a dummy widget
dummy.pack()
frame = Frame(root, width=100, height=100)
frame.bind("<space>",beep)
frame.pack()
frame.focus_set()

root.mainloop()

我已经对其进行了评论以更好地理解,但这只是一种解决方法,而且理解起来也不那么复杂.

I've commented it to understand better, but this is just a way around and its not that complicated to understand either.

还要记住,在所有使用winsound的情况下,只要那个哔哔声开始并播放完毕,GUI就会无响应,即GUI将无响应1秒(在你的情况下).

Also keep in mind, in all cases of using winsound, as long as that beep has started and finished playing, the GUI will be unresponsive, that is, GUI will be unresponsive for 1 sec(in your case).

这篇关于Tkinter 解除绑定键事件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆