Building a Caps Lock and Num Lock Indicator with Python


Introduction:

In the realm of user interface design, small yet functional utilities can greatly enhance user experience. One such utility is the Caps Lock and Num Lock indicator, which provides real-time feedback to users about the status of these keys. In this tutorial, we'll explore how to build a Caps Lock and Num Lock indicator using Python's Tkinter library.

 

Prerequisites:

To follow along with this tutorial, you should have a basic understanding of Python programming and the Tkinter library. Additionally, this tutorial is tailored for Windows users due to its dependency on system-level functions to detect key states.

 

Setting Up the Environment:

First, ensure you have Python installed on your system. Tkinter usually comes pre-installed with Python, so no additional installation steps are necessary. You can verify the installation by running `import tkinter` in a Python interpreter.

 

Creating the Application:

We'll start by creating a Tkinter application that displays the Caps Lock and Num Lock status in a small window. The code provided in this tutorial will create a minimalist yet functional Caps Lock and Num Lock indicator.

  • Copy the below code and  paste it to notepad and save it as capslock.py and run the capslock.py
  • To exit the Application Press ESC



import tkinter as tk
from tkinter import ttk
import ctypes

class CapsNumLockIndicator(tk.Tk):
    def __init__(self):
        super().__init__()
        
        # Initialize variables for dragging
        self._drag_start_x = 0
        self._drag_start_y = 0
        
        # Set window properties
        self.title("Caps & Num Lock Indicator")
        self.geometry("150x50")
        self.configure(bg="#383838")  
        self.overrideredirect(True)  
        self.attributes("-topmost", True)  
        self.resizable(False, False)  
        
        # Create style
        self.style = ttk.Style()
        
        # Configure style for labels
        self.style.configure("CapsLabel.TLabel", foreground="#FF4500", background="#383838", font=("Arial", 8))
        self.style.configure("NumLabel.TLabel", foreground="#32CD32", background="#383838", font=("Arial", 8))
        
        # Create label for Caps Lock indicator
        self.caps_label = ttk.Label(self, text="CAPS LOCK", style="CapsLabel.TLabel")
        self.caps_label.pack(side=tk.TOP, pady=2)
        
        # Create label for Num Lock indicator
        self.num_label = ttk.Label(self, text="NUM LOCK", style="NumLabel.TLabel")
        self.num_label.pack(side=tk.TOP, pady=2)
        
        # Bind mouse events for dragging
        self.bind("<ButtonPress-1>", self.start_move)
        self.bind("<B1-Motion>", self.on_move)
        
        # Bind keyboard event to close window (Escape key)
        self.bind("<Escape>", self.close_window)
        
        # Check Caps Lock and Num Lock status
        self.update_status()
        
        # Update status every 200 milliseconds
        self.after(200, self.update_status)
        
    def start_move(self, event):
        self._drag_start_x = event.x
        self._drag_start_y = event.y
        
    def on_move(self, event):
        x = self.winfo_pointerx() - self._drag_start_x
        y = self.winfo_pointery() - self._drag_start_y
        
        # Adjust position to stay within screen boundaries
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()
        
        if x < 0:
            x = 0
        elif x + self.winfo_width() > screen_width:
            x = screen_width - self.winfo_width()
        
        if y < 0:
            y = 0
        elif y + self.winfo_height() > screen_height:
            y = screen_height - self.winfo_height()
        
        self.geometry("+{}+{}".format(x, y))
        
    def update_status(self):
        # Check Caps Lock status
        caps_lock_state = ctypes.windll.user32.GetKeyState(0x14) & 0xffff != 0
        if caps_lock_state:
            self.caps_label.config(text="CAPS LOCK: ON", foreground="#32CD32")  
        else:
            self.caps_label.config(text="CAPS LOCK: OFF", foreground="#FF4500")  
        
        # Check Num Lock status
        num_lock_state = ctypes.windll.user32.GetKeyState(0x90) & 0xffff != 0
        if num_lock_state:
            self.num_label.config(text="NUM LOCK: ON", foreground="#32CD32")  
        else:
            self.num_label.config(text="NUM LOCK: OFF", foreground="#FF4500")  
        
        # Schedule the next update
        self.after(200, self.update_status)
        
    def close_window(self, event):
        self.destroy()

# Create and run the application
app = CapsNumLockIndicator()
app.mainloop()



Explanation:

- We define a class `CapsNumLockIndicator` that inherits from `tk.Tk`, representing the main application window.

- The constructor `__init__` sets up the window properties, creates labels for Caps Lock and Num Lock indicators, and binds mouse and keyboard events.

- The `update_status` method checks the Caps Lock and Num Lock statuses using `ctypes.windll.user32.GetKeyState` and updates the labels accordingly.

- Finally, we create an instance of `CapsNumLockIndicator` and start the application loop using `mainloop()`.



Conclusion:

In this tutorial, we've learned how to create a Caps Lock and Num Lock indicator using Python's Tkinter library. This small utility can be a handy addition to any desktop application, providing users with real-time feedback on the status of these keys. With a minimalist design and straightforward implementation, it's a perfect example of how Python and Tkinter can be used to build functional yet user-friendly GUI applications. Feel free to customize the code further to suit your specific requirements and preferences.





Comments

Popular posts from this blog

Displaying a Calendar in the Command Prompt Using Python

How to Create a Simple File Listing Script with VBScript