Python+Tkinter中的光标事件处理

1 投票
2 回答
4182 浏览
提问于 2025-04-11 09:29

我正在写一段代码,希望能在用户把光标从一个输入框(Entry widget)移开时生成一个事件,比如移到另一个输入框、按钮等等。

到目前为止,我只想到可以绑定TAB键和鼠标点击,不过如果我把鼠标点击绑定到输入框上,只有在输入框内部点击时才能捕捉到鼠标事件。

我该如何实现当一个控件失去光标焦点时生成事件呢?

提前谢谢大家!

2 个回答

0

这不是专门针对tkinter的,也不是关于焦点的问题,但我在这里找到了一个类似问题的答案:

使用Python检测Windows中的鼠标点击

我已经有一段时间没用tkinter了,但似乎有“FocusIn”和“FocusOut”这两个事件。你可以试着绑定这些事件并跟踪它们,可能能解决你的问题。

来源: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

5

<FocusIn> 和 <FocusOut> 这两个事件正是你需要的。运行下面的例子,你会发现无论是点击鼠标还是按下 Tab 键(或者 Shift + Tab 键),只要焦点在某个输入框上,就会触发这些事件。

from Tkinter import *

def main():
    global text

    root=Tk()

    l1=Label(root,text="Field 1:")
    l2=Label(root,text="Field 2:")
    t1=Text(root,height=4,width=40)
    e1=Entry(root)
    e2=Entry(root)
    l1.grid(row=0,column=0,sticky="e")
    e1.grid(row=0,column=1,sticky="ew")
    l2.grid(row=1,column=0,sticky="e")
    e2.grid(row=1,column=1,sticky="ew")
    t1.grid(row=2,column=0,columnspan=2,sticky="nw")

    root.grid_columnconfigure(1,weight=1)
    root.grid_rowconfigure(2,weight=1)

    root.bind_class("Entry","<FocusOut>",focusOutHandler)
    root.bind_class("Entry","<FocusIn>",focusInHandler)

    text = t1
    root.mainloop()

def focusInHandler(event):
    text.insert("end","FocusIn %s\n" % event.widget)
    text.see("end")

def focusOutHandler(event):
    text.insert("end","FocusOut %s\n" % event.widget)
    text.see("end")


if __name__ == "__main__":
    main();

撰写回答