Tkinter 中 focus 和 focus_set 方法有什麼區別?


Focus 用於指代當前接受輸入的小元件或視窗。小元件可用於限制滑鼠移動、搶佔焦點和超出邊界的擊鍵操作。但如果我們想要讓小元件獲得焦點以啟用它接受輸入,那麼我們就可以使用 focus.set() 方法。focus() 有時會被稱作 focus_set()

當小元件的視窗或小元件獲得焦點時,focus_set() 會讓焦點聚焦在該小元件上。

示例

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Define a function to set the focus
def set_focus():
   entry.focus_set()

# Create an Entry widget
entry=Entry(win, width=35)
   entry.pack()

# Create a Button to get the focus on any widget
ttk.Button(win, text="Set Focus", command=set_focus).pack()

win.mainloop()

輸出

執行上述程式碼將會顯示一個帶有按鈕和小元件視窗的視窗。當我們單擊按鈕時,它將把焦點設定在小元件視窗上。

更新時間: 2021 年 6 月 18 日

1K+ 瀏覽量

啟動你的職業生涯

透過完成課程取得認證。

開始
廣告
© . All rights reserved.