[英]How to prompt user that caps lock is enabled
當我將光標放在條目小部件但不知道如何解決這個問題時,我試圖檢測大寫鎖定。
我在網站上找到了這些答案,但沒有一個滿足我的需求: 大寫鎖定和移位鍵狀態和當前鍵鎖狀態
from tkinter import *
root = Tk()
root.geometry("400x400")
e1 = Entry(root, width=40)
e1.focus()
e1.pack()
e2 = Entry(root, width=40)
e2.place(x=70, y=100)
root.mainloop()
我歡迎你提出如何做到這一點的建議。
您可以使用條目上的綁定來檢測用戶是否使用大寫鎖定鍵入。 事件修飾符Lock
使您只有在大寫鎖定打開時才能觸發事件。 因此,通過將警告綁定到'<Lock-KeyPress>'
,每次用戶在按下大寫鎖定時按下按鍵時,都會顯示該警告。 如果您希望警告只顯示一次,只需在with_caps_lock
取消綁定該事件with_caps_lock
。
這是一個例子:
import tkinter as tk
def with_caps_lock(event):
if event.keysym != "Caps_Lock":
# this if statetement prevent the warning to show up when the user
# switches off caps lock
print('WARNING! Caps Lock is on.')
# unbind to do it only once
e1.unbind('<Lock-KeyPress>', bind_id)
root = tk.Tk()
root.geometry("400x400")
e1 = tk.Entry(root, width=40)
e1.focus()
e1.pack()
# show warning when the user types with caps lock on
bind_id = e1.bind('<Lock-KeyPress>', with_caps_lock)
root.mainloop()
僅適用於Windows:
from tkinter import *
import ctypes
hllDll = ctypes.WinDLL ("User32.dll")
VK_CAPITAL = 0x14
def get_capslock_state():
return hllDll.GetKeyState(VK_CAPITAL)
def on_focus(event):
if (get_capslock_state()):
print("Caps lock is on")
root = Tk()
root.geometry("400x400")
e1 = Entry(root, width=40)
e1.focus()
e1.pack()
e2 = Entry(root, width=40)
e2.place(x=70, y=100)
e2.bind("<FocusIn>", on_focus)
root.mainloop()
使用@ _4321提供的答案,如果啟用大寫鎖定,則可以將其顯示為Label
如果您不想提示用戶,則可以將其顯示為禁用。如果您不想打印到終端,請參閱此方法。
import tkinter as tk
def with_caps_lock(event):
if event.keysym != "Caps_Lock":
ID["text"]= "cap is on man"
elif event.keysym == "Caps_Lock":
ID["text"]= "caps is off wowowow"
root = tk.Tk()
root.geometry("400x400")
ID = tk.Label(root, foreground="RED")
ID.place(x=100, y=100)
e1 = tk.Entry(root, width=40)
e1.focus()
e1.pack()
# show warning when the user types with caps lock on
e1.bind('<Lock-KeyPress>', with_caps_lock)
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.