如何將焦點賦予 Python Tkinter 文字小部件?
在各種應用程式中,需要使 tkinter 小部件獲取焦點,以便啟用它們。小部件還可以獲取焦點,並阻止邊界外部的其他事件。我們通常使用 focus_set() 方法來管理特定小部件並賦予其焦點。它使小部件獲取焦點並激活小部件,直至程式終止。
示例
在以下示例中,我們在同一視窗中建立了兩個小部件:一個 Entry 小部件和一個文字小部件。透過使用 focus_set() 方法,我們將在文字小部件中啟用焦點。
#Import tkinter library from tkinter import * from PIL import Image,ImageTk #Create an instance of tkinter frame win = Tk() #Set the geometry win.geometry("750x250") #Create a Text WIdget text= Text(win, width= 30, height= 10) text.insert(INSERT, "Hello World!") #Activate the focus text.focus_set() text.pack() #Create an Entry Widget entry=Entry(win,width= 30) entry.pack() win.mainloop()
結果
執行以上程式碼,將顯示一個包含文字小部件焦點的視窗。
廣告