如何在 tkinter 中顯示 Caps Lock 鍵的狀態?


我們可以使用 <Lock-KeyPress><Lock-KeyRelease> 繫結來檢查 Caps Lock 鍵是否開啟或關閉。在以下示例中,我們將建立兩個使用者定義的函式 “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 時,它將顯示其當前狀態,無論是開啟還是關閉。

更新於:2021 年 10 月 26 日

801 次瀏覽

職業騰飛

完成本課程以獲得認證

開始
廣告