a lonzo
a lonzo

Reputation: 11

Python issue with CTRL-V in Tkinter Entry widget

In the Entry widget, I tried to restrict values to only hexadecimal using validatecommand and a function to verify if the entry value is in 'abcdef0123456789'. The problem lies in the fact that "CTRL+V" (Paste) doesn't work when I use it to insert value. There is no problem with "CTRL+C" and "CTRL+X" (Copy and Cut).

Is that a way to restrict the entry to hexadecimal value and in same time allow the use of CTRL-V to Paste/insert value?

Upvotes: 0

Views: 1743

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

Is that a way to restrict the entry to hexadecimal value and in same time allow the use of CTRL-V to Paste/insert value?

Yes. Arguably the simplest method is to use the validatecommand to check that all of the characters in the widget are hex digits. The validatecommand doesn't care how the characters are entered (typing vs cut/paste).

In the following example, '%P' tells tkinter to pass the new value of the entry widget if the edit is allowed. We can then use the re module to see if the new value is composed of only zero or more hex digits.

import tkinter as tk
import re

def validate(possible_new_value):
    if re.match(r'^[0-9a-fA-F]*$', possible_new_value):
        return True
    return False

root = tk.Tk()
entry = tk.Entry(root, validate="key", 
                 validatecommand=(root.register(validate), '%P'))
entry.pack(padx=20, pady=20)
root.mainloop()

Upvotes: 1

Related Questions