我有一个使用tkinter和按键绑定的Python程序。程序调用外部程序,然后询问如何处理它,期望按下n键表示“否”或y键表示“是”。问题在于:如果我按两次允许的键,则第二个键将被存储并稍后处理 - 因此适用于错误的问题。
import tkinter as tk
import time
class App:
counter = 0
def __init__(self, master): # Constructor
# build GUI
self.label = tk.Label(text="Press <space>", width=40)
self.label.grid(row=1, column=1, sticky='w')
# bind keys to buttons
master.bind('<Key-space>', self.keyPressed)
pass # __init__
def keyPressed(self, event):
print("Step 1")
self.counter = self.counter + 1
self.label.configure(text = str(self.counter))
self.label.update()
time.sleep(3)
print("Step 2")
pass # Key1Pressed
# End of class App
root = tk.Tk()
root.option_add('*font', ('Arial', 11, 'bold'))
# root.attributes("-toolwindow", 1)
posX = root.winfo_screenwidth() - 500
posY = 30
root.geometry("+%d+%d" % (posX, posY))
root.title("Bind tester")
display = App(root)
root.mainloop()
在上述代码片段中,我用 sleep() 函数替换了外部程序,并更改了空格键绑定。如果启动 python3 脚本并在休眠期间连续按两次空格键,则会在终端中看到输出结果,如下所示:
Step 1
Step 2
Step 1
Step 2
我希望在睡眠过程中忽略所有引发的按键事件。所以我试用信号量,但是也没有成功。问题可能更加复杂,因为如果我在睡眠期间连续按下空格键三次,会得到以下结果:
Step 1
Step 2
Step 1
Step 1
Step 2
Step 2
看起来函数keypressed在同时被调用多次。是否有可能在接受新事件之前清除事件队列?
return "break"
就足以防止tkinter.Entry
小部件在插入新文本以进行自动完成功能后自动选择文本。 - tom_mai78101