如何檢查 Tkinter 中的小元件是否具有焦點?


假設我們需要檢查特定小元件是否具有焦點集。檢查小元件焦點的唯一方法是使用實用方法 focus_get()。它會返回包含小元件資訊的變數,這些資訊在程式執行期間會作為小元件的焦點。在程式執行期間,我們將使用 focus_get() 方法找到活動小元件。

示例

在此示例中,我們建立了一個 Entry 小元件,當按下 <Enter> 鍵時,它將獲取焦點。focus_get() 方法將會返回當前活動小元件的資訊。

#Import the Tkinter library
from tkinter import *
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
win.geometry("750x250")
#Define Event handlers for different Operations
def event_show(event):
   label.config(text="Hello World")
   e.focus_set()
   print("focus is:" ,e.focus_get)
#Create a Label
label= Label(win, text="Press Enter",font=('Helvetica 15 underline'))
label.pack()
#Create an entry widget
e= Entry(win, width= 25)
e.pack(pady=20)
#Bind the function
win.bind('<Return>',lambda event:event_show(event))
win.mainloop()

輸出

執行上述程式碼將會顯示一個包含按鈕的視窗。當按下 <Enter> 鍵時,它會列印包含小元件資訊(當前視窗窗格的焦點)的輸出。

現在,當按下 <Enter> 時,它將在 Shell 中顯示輸出,如:

focus is : <bound method Misc.focus_get of <tkinter.Entry object .!entry >>

更新於:21-Apr-2021

2K+ 瀏覽量

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告