默認情況下,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
方法綁定到一個鼠標點擊事件這樣做需要保留對你的小部件的引用,就像我上面用變量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
來使每個小部件都可以使用單擊時單擊yboard焦點(或者,如果您只希望某些類型的小部件執行此操作,則可以使用bind_class
)。
只需添加這行:
top.bind_all("<1>", lambda event:event.widget.focus_set())
謝謝。但是有全球解決方案嗎?就像我說的,假設有很多小部件,不僅有三個。 – user3654650
當然。發佈另一個解決方案 - 這是否符合您的要求? – Brionius
@Bionion Iteresting問題。我編輯了這個問題,因爲我認爲OP要求非常一般的解決方案。 – Marcin