从条目小部件中删除焦点 [英] Remove focus from Entry widget

查看:26
本文介绍了从条目小部件中删除焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have simple example, Entry and three separate Frames.

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 之外只有三个小部件.但假设有很多小部件.

Once I start writing in Entry, the keyboard cursor stay there, even when I press with mouse on blue, green or yellow Frame. How to stop writing in Entry, when mouse presses another widget? In this example only three widgets except Entry. But assume there is alot of widgets.

推荐答案

默认情况下,Frames 不占用键盘焦点.然而,如果你想在点击时给它们键盘焦点,你可以通过将 focus_set 方法绑定到鼠标点击事件来实现:

By default, Frames do not take keyboard focus. However, if you want to give them keyboard focus when clicked on, you can do so by binding the focus_set method to a mouse click event:

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()

请注意,要做到这一点,您需要保留对小部件的引用,就像我在上面对变量 bgy<所做的那样/代码>.

Note that to do this you'll need to keep references to your widgets, as I did above with the variables b, g, and y.

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

Here is another solution, accomplished by creating a subclass of Frame that is able to take keyboard focus:

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这样做).


Option 3

A third option is to just use bind_all to make every single widget take the keyboard focus when clicked (or you can use bind_class if you only want certain types of widgets to do this).

只需添加这一行:

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

这篇关于从条目小部件中删除焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆