2014-06-06 55 views
0

我有一個簡單的例子,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。但是,假設有很多小部件。

回答

5

默認情況下,Frames不佔用鍵盤焦點。

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

注意,要做到這一點,你會:但是,如果你想給他們鍵盤焦點的時候點擊,您可以通過focus_set方法綁定到一個鼠標點擊事件這樣做需要保留對你的小部件的引用,就像我上面用變量bgy所做的那樣。


選項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來使每個小部件都可以使用單擊時單擊yboard焦點(或者,如果您只希望某些類型的小部件執行此操作,則可以使用bind_class)。

只需添加這行:

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

謝謝。但是有全球解決方案嗎?就像我說的,假設有很多小部件,不僅有三個。 – user3654650

+0

當然。發佈另一個解決方案 - 這是否符合您的要求? – Brionius

+0

@Bionion Iteresting問題。我編輯了這個問題,因爲我認爲OP要求非常一般的解決方案。 – Marcin