Python focus_set()和focus_get()方法用法介绍

2021年3月17日14:19:49 发表评论 2,773 次浏览

本文概述

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()

输出如下:

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

你可能在上图中观察到按钮小部件有重点。为了更好地理解, 请复制并运行以上程序.

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

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: