Skip to main content
 首页 » 编程设计

python之从 Entry 小部件中移除焦点

2025年05月04日18jillzhang

我有一个简单的例子,Entry 和三个独立的框架。

from tkinter import * 
 
top = Tk() 
 
Entry(top, width="20").pack() 
Frame(top, width=200, height=200, bg='blue').pack() 
Frame(top, width=200, height=200, bg='green').pack() 
Frame(top, width=200, height=200, bg='yellow').pack()  
# Some extra widgets    
Label(top, width=20, text='Label text').pack() 
Button(top, width=20, text='Button text').pack() 
 
top.mainloop() 

一旦我开始在 Entry 中书写,键盘光标就会停留在那里,即使我用鼠标在蓝色、绿色或黄色框架上按下也是如此。当鼠标按下另一个小部件时,如何停止在 Entry 中写入?在这个例子中只有三个小部件,除了 Entry。但假设有很多小部件。

请您参考如下方法:

默认情况下,Frames 不获取键盘焦点。然而,如果你想在点击时给予他们键盘焦点,你可以通过将 focus_set 方法绑定(bind)到鼠标点击事件来实现:

选项 1

from tkinter import * 
 
top = Tk() 
 
Entry(top, width="20").pack() 
b = Frame(top, width=200, height=200, bg='blue') 
g = Frame(top, width=200, height=200, bg='green') 
y = Frame(top, width=200, height=200, bg='yellow') 
 
b.pack() 
g.pack() 
y.pack() 
 
b.bind("<1>", lambda event: b.focus_set()) 
g.bind("<1>", lambda event: g.focus_set()) 
y.bind("<1>", lambda event: y.focus_set()) 
 
top.mainloop() 

请注意,要做到这一点,您需要保留对小部件的引用,就像我在上面对变量 b、g 和 y< 所做的那样.


选项 2

这是另一种解决方案,通过创建能够获取键盘焦点的 Frame 的子类来实现:

from tkinter import * 
 
class FocusFrame(Frame): 
    def __init__(self, *args, **kwargs): 
        Frame.__init__(self, *args, **kwargs) 
        self.bind("<1>", lambda event: self.focus_set()) 
 
top = Tk() 
 
Entry(top, width="20").pack() 
FocusFrame(top, width=200, height=200, bg='blue').pack() 
FocusFrame(top, width=200, height=200, bg='green').pack() 
FocusFrame(top, width=200, height=200, bg='yellow').pack()     
 
top.mainloop() 

选项 3

第三种选择是只使用 bind_all 让每个小部件在点击时获得键盘焦点(或者如果您只想要某些类型的小部件,您可以使用 bind_class这样做)。

只需添加这一行:

top.bind_all("<1>", lambda event:event.widget.focus_set())