1
在下面的代码中有两种方法,一种是捕获鼠标点击,另一种是按键。我想focus_set按键而不是鼠标点击,但如果我在按键功能中使用focus_set,那么它不起作用。但如果我把它放在鼠标点击它的作品和关键功能工作得很好。python Tkinter 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()
感谢您的答案,我也想知道,如果我从key方法返回文本值,然后在方法外部创建一个新变量,如a = key(“what will the parameter?”),因为函数以事件对象为参数。这个关键方法的参数应该是什么 –
@ MD.FazlaRabby:由于'key'使用来自事件的数据,所以如果你想直接调用它并保存返回值,你将不得不传递一个对象因为这是你的回调要求,所以它有一个'char'参数。 –
感谢您的回复,python是否有一个“char”变量?如果你能给我一个演示/例子,这将会非常有帮助 –