在 Tkinter 中將焦點從一個 Text 部件切換到另一個 Text 部件
在各種應用程式中,需要讓 tkinter 部件獲得焦點才能使其處於活動狀態。部件還可以搶奪焦點並阻止邊界之外的其他事件。為了管理和給予特定部件焦點,我們通常使用 focus_set() 方法。它使部件獲得焦點並使其在程式終止之前處於活動狀態。
示例
在以下示例中,我們建立了兩個文字部件,我們將使用 按鈕 部件同時將焦點從一個文字部件更改為另一個文字部件。因此,透過定義可以透過 按鈕 部件處理的兩個方法可以很方便地更改焦點。
#Import tkinter library from tkinter import * #Create an instance of tkinter frame win = Tk() #Set the geometry win.geometry("750x250") #Define a function for changing the focus of text widgets def changeFocus(): text1.focus_set() button.config(command=change_focus, background= "gray71") def change_focus(): text2.focus_set() button.configure(command= changeFocus) #Create a Text WIdget text1= Text(win, width= 30, height= 5) text1.insert(INSERT, "New Line Text") #Activate the focus text1.focus_set() text1.pack() #Create another text widget text2= Text(win, width= 30, height=5) text2.insert(INSERT,"Another New Line Text") text2.pack() #Create a Button button= Button(win, text= "Change Focus",font=('Helvetica 10 bold'), command= change_focus) button.pack(pady=20) win.mainloop()
輸出
執行上述程式碼將顯示一個包含兩個文字部件的視窗。最初,“text1”部件將具有活動焦點。
現在單擊“更改焦點”按鈕以在兩個文字部件之間切換焦點。
廣告