如何在 tkinter 中显示 CAPS Lock Key 的状态?

我们可以使用<Lock-KeyPress><Lock-KeyRelease>绑定来检查 CAPS 锁定键是打开还是关闭。在下面的示例中,我们将创建两个用户定义的函数“ caps_lock_on()”“ caps_lock_off()”,它们将捕获 Lock-KeyPress 和 Lock-KeyRelease 的事件并在屏幕上打印状态。

示例

# Import required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()

# Define the geometry of the window
win.geometry("700x250")

win.title("CAPS Lock Status")

def caps_lock_on(e):
   label_caps.config(text="CAPS Lock is ON")

def caps_lock_off(e):
   label_caps.config(text="CAPS Lock is OFF")

label_caps = Label(win, font="Helvetica 15 bold")
label_caps.pack(pady=20)

win.bind("<Lock-KeyPress>", caps_lock_on)
win.bind("<Lock-KeyRelease>", caps_lock_off)

win.mainloop()
输出结果

当用户按下 CAPS Lock 时,它将显示其当前状态,无论是 ON 还是 OFF。