为指定的 Tkinter 输入小组件设定焦点
Tkinter 有很多通用的方法,可以为小组件和元素添加功能。为了将焦点设定在特定的窗口小部件上,我们有 focus_set() 方法,该方法用于在一个应用程序中存在的窗口小部件组中框定一个特定的窗口小部件。
示例
在这个例子里,我们在 0-9 的范围内创建了数字键。我们已经设置焦点到数字键“2”。
#Import the required libraries
from tkinter import *
import webbrowser
#Create an instance of tkinter frame
win = Tk()
win.geometry("750x400")
#Define function for different operations
def close():
win.destroy()
#Create a Label widget
text=Label(win, text="", font=('Helvetica bold ',25))
text.place(x= 110, y= 50,)
#Create Button widgets
b1=Button(win, text= "1")
b1.place(x=220, y=20)
b2=Button(win, text= "2")
b2.place(x=250, y=20)
b3=Button(win, text= "3")
b3.place(x=280, y=20)
b4=Button(win, text= "4")
b4.place(x=220, y=50)
b5=Button(win, text= "5")
b5.place(x=250, y=50)
b6=Button(win, text= "6")
b6.place(x=280, y=50)
b7=Button(win, text= "7")
b7.place(x=280, y=80)
b8=Button(win, text= "8")
b8.place(x=250, y=80)
b9=Button(win, text= "9")
b9.place(x=280, y=80)
b0=Button(win, text= "0")
b0.place(x=220, y=80)
#Set the focus on button b1
b2.focus_set()
b2=Button(win, text= "Close", command= close)
b2.place(x=240,y= 140)
win.mainloop()输出
运行上面的代码会显示数字键“2”的焦点。

要改变窗口小部件的焦点,只需要在你想要设定焦点的小部件上添加 focus_set.() 方法。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP