当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。