當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python focus_set() and focus_get()用法及代碼示例


Tkinter具有許多可在任何GUI中提供函數的小部件。它還支持多種通用小部件方法,這些方法可以應用於任何小部件。
focus_get()focus_set()方法也是通用的窗口小部件方法。它們也可以應用於Tk()方法。

focus_set()方法-

當且僅當主窗口被聚焦時,此方法用於將焦點設置在所需的小部件上。

用法:


widget.focus_set()

以下是Python程序-

# Importing tkinter module 
# and all functions 
from tkinter import * 
from tkinter.ttk import *
  
# creating master window 
master = Tk() 
  
# Entry widget 
e1 = Entry(master) 
e1.pack(expand = 1, fill = BOTH) 
  
# Button widget which currently has the focus 
e2 = Button(master, text ="Button") 
  
# here focus_set() method is used to set the focus 
e2.focus_set() 
e2.pack(pady = 5) 
  
# Radiobuton widget 
e3 = Radiobutton(master, text ="Hello") 
e3.pack(pady = 5) 
  
# Infinite loop 
mainloop()

輸出:

您可能在上圖中觀察到Button小部件具有焦點。為了更好地理解,請複製並運行以上程序。

focus_get()方法-

此方法返回當前具有焦點的窗口小部件的名稱。

用法:

master.focus_get()

注意:您可以將其與任何窗口小部件一起使用,無需使用主窗口。

以下是Python程序-

# Importing tkinter module 
# and all functions 
from tkinter import * 
from tkinter.ttk import *
  
# creating master window 
master = Tk() 
  
# This method is used to get 
# the name of the widget 
# which currently has the focus 
# by clicking Mouse Button-1 
def focus(event):
    widget = master.focus_get() 
    print(widget, "has focus") 
  
# Entry widget 
e1 = Entry(master) 
e1.pack(expand = 1, fill = BOTH) 
  
# Button Widget 
e2 = Button(master, text ="Button") 
e2.pack(pady = 5) 
  
# Radiobutton widget 
e3 = Radiobutton(master, text ="Hello") 
e3.pack(pady = 5) 
  
# Here function focus() is binded with Mouse Button-1 
# so every time you click mouse, it will call the 
# focus method, defined above 
master.bind_all("<Button-1>", lambda e:focus(e)) 
  
# infinite loop 
mainloop()

輸出:每次您單擊任何窗口小部件時,或者如果您單擊上麵的程序的鼠標按鈕-1,都將打印具有焦點的窗口小部件的名稱。為了更好地理解,請複製並運行以上程序。

.!radiobutton has focus
.!entry has focus
.!button has focus


相關用法


注:本文由純淨天空篩選整理自sanjeev2552大神的英文原創作品 Python | focus_set() and focus_get() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。