📜  Python| focus_set() 和 focus_get() 方法

📅  最后修改于: 2022-05-13 01:54:38.978000             🧑  作者: Mango

Python| focus_set() 和 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("", lambda e: focus(e))
  
# infinite loop
mainloop()

输出:每次单击任何小部件时,或者如果单击上面的鼠标按钮-1,程序将打印具有焦点的小部件的名称。为了更好地理解复制和运行上面的程序。

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