[英]How to prompt user that caps lock is enabled
Am trying to detect the the caps lock is on when I place the cursor in the entry widget but don't know how to go about this. 当我将光标放在条目小部件但不知道如何解决这个问题时,我试图检测大写锁定。
I found these answers on the site but none satisfy my needs: caps locks ans shift key status and current key lock status 我在网站上找到了这些答案,但没有一个满足我的需求: 大写锁定和移位键状态和当前键锁状态
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()
I welcome your suggestion on how to do this. 我欢迎你提出如何做到这一点的建议。
You can detect if the user is typing with caps lock on using a binding on the entry. 您可以使用条目上的绑定来检测用户是否使用大写锁定键入。 The event modifier
Lock
enable you to trigger the event only if caps lock is on. 事件修饰符
Lock
使您只有在大写锁定打开时才能触发事件。 So by binding your warning to '<Lock-KeyPress>'
, it will be shown each time the user presses a key while caps lock is on. 因此,通过将警告绑定到
'<Lock-KeyPress>'
,每次用户在按下大写锁定时按下按键时,都会显示该警告。 If you want the warning to be displayed only once, just unbind the event in with_caps_lock
. 如果您希望警告只显示一次,只需在
with_caps_lock
取消绑定该事件with_caps_lock
。
Here is an example: 这是一个例子:
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()
For windows only: 仅适用于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()
With the answer provided by @_4321 you can display it as a Label
if the Caps lock is enabled or Disabled to prompt the user .If you don't want to print to the terminal this how to go about this. 使用@ _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.