简体   繁体   中英

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. So by binding your warning to '<Lock-KeyPress>' , it will be shown each time the user presses a key while caps lock is on. If you want the warning to be displayed only once, just unbind the event in 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:

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM