python Tkinter focus_set()在捕获按键事件时无法正常工作

时间:2017-08-17 08:31:29

标签: python python-3.x user-interface tkinter setfocus

下面的代码中有两种方法,一种用于捕获鼠标,另一种用于按键。我想集中注意按键而不是鼠标点击,但是如果我在按键功能中使用focus_set那么它就不起作用了。但是,如果我把它放在鼠标内部,它就可以正常工作,关键功能也可以正常使用。

from tkinter import *
root = Tk()

text = ''
frame = Frame(root, width=100, height=100)


def key(event):

    frame.focus_set() # here is the focus set which is not working
    global text

    text += event.char
    print (test)

def callback(event):
    #but If I put that same line here, it works
    print ("clicked at", event.x, event.y)

frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()

root.mainloop()

1 个答案:

答案 0 :(得分:1)

focus_set仅影响调用后触发的事件,它仅影响键盘事件,而不影响鼠标点击。在事件处理程序中调用它不会影响正在处理的事件。