Home > database >  Dynamically formating text entered in a tk.Entry
Dynamically formating text entered in a tk.Entry

Time:01-27

I'm trying to dynamically format data entered within a tk.Entry. I know you can hook up a StringVar to the widget for access and bind an event to it but I'm unable to format the entry properly. In this case I'm trying to format and entered phone number while I'm typing. I want brackets around the area code, space before the next 3 numbers and a dash before the last 4.

(999) 999-9999

The binding with the event does work and I'm able to access the entered character but placement within the widget dynamically just doesn't work for me.

Python Code

def fmatphone(event):
    fphone = "("   landline.get()
    landline.set(fphone)

landline = StringVar()

phonelentry = tk.Entry(
    framebody,
    justisfy="left",
    bg="#DCDCDC",
    fg="black",
    width=13,
    textvariable=landline)

phonelentry.grid(row=6, column=0, padx=250, pady=4, sticky="w")
phonelentry.bind("<Key>", fmatphone)

When I enter a 9 in phoneLentry the entry shows up a 9( instead of the reverse. Kind of like a timing issue or something. I might be going about this all wrong so please feel free to set me straight.

CodePudding user response:

import pynput.keyboard

def fmatphone(event):

    key_pressed = event.keysym

    if key_pressed not in "0123456789":

        keyboard = Controller()
        keyboard.press(pynput.keyboard.Key.backspace)
        keyboard.release(pynput.keyboard.Key.backspace)

        keyboard = None

phonelentry = tk.Entry(
    framebody,
    justisfy="left",
    bg="#DCDCDC",
    fg="black",
    width=13,
    textvariable=landline)

phonelentry.grid(row=6, column=0, padx=250, pady=4, sticky="w")
phonelentry.bind("<Key>", fmatphone)

CodePudding user response:

Try this:

import re
print('(%s) %s-%s' % tuple(re.findall(r'\d{4}$|\d{3}', '9999999999')))

Output: (999) 999-9999

If you want to use function.

Code:

import re

def phone_number(phone):
    return re.sub(r'(?<!\S)(\d{3})-', r'(\1) ', phone)
  • Related