0

I am trying to add limitation on an Entry widget, like only 11 digits are allowed to be entered. I had tried this:

import tkinter as tk 
from tkinter import ttk 
from tkinter import messagebox

root=tk.Tk()


string=tk.StringVar()
def limit(string):
    if len(string.get())>11:
        messagebox.showinfo('invalid input (should be 11 digits')


label=tk.Label(root,text="Phone Number:",font=20,bg="#33BEFF")
label.pack()
phno=ttk.Entry(root,textvariable=string,text="",command=limit)
phno.pack()

root.mainloop()

I want that only 11 digits should be entered in an Entry.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Super
  • 23
  • 1
  • 8

2 Answers2

0
import tkinter as tk
from tkinter import *
root=tk.Tk()


string = tk.StringVar()

max_len = 11
def on_write(*args):
    s = string.get()
    if len(s) > max_len:
        string.set(s[:max_len])

string.trace_variable("w", on_write)

label=tk.Label(root,text="Phone Number:",font=20,bg="#33BEFF")
label.pack()


phno = tk.Entry(root, textvariable=string)
phno.pack()

root.mainloop()

Tell the StringVar to call the function on_write() every time its value is changed. So every time the user edits the data in the Entry, in turn the Entry changes the data of the StringVar, which calls the on_write() function which may or may not change the StringVar -- and that change is reflected in what the Entry displays

ncica
  • 7,015
  • 1
  • 15
  • 37
  • This allows non-digts to be entered — so it's at best incomplete. Also, the OP's question has been closed as a duplicate, so they can't accept an answer. – martineau Sep 06 '19 at 07:22
0

You can add validation to Entry widgets. Here's a little documentation, and here's how it could be applied in this case.

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox


def limit(text):
    """ Determine if inp string is a valid integer (or empty) and is no more
        than MAX_DIGITS long.
    """
    MAX_DIGITS = 11

    try:
        int(text)  # Valid integer?
    except ValueError:
        valid = (text == '')  # Invalid unless it's just empty.
    else:
        valid = (len(text) <= MAX_DIGITS)   # OK unless it's too long.

    if not valid:
        messagebox.showinfo('Entry error',
                            'Invalid input (should be {} digits)'.format(MAX_DIGITS),
                            icon=messagebox.WARNING)
    return valid


root = tk.Tk()
root.geometry('200x100')  # Initial size of root window.

label = tk.Label(root, text="Phone Number:", font=20, bg="#33BEFF")
label.pack()

reg = root.register(limit)  # Register Entry validation function.
string = tk.StringVar()
phno = ttk.Entry(root, textvariable=string, text="",
                 validate='key', validatecommand=(reg, '%P'))
phno.pack()
phno.focus_set()  # Set initial input focus to this widget.

root.mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301