limit the number of digits Entry - Tkinter

Asked

Viewed 926 times

0

Hello.

How do I limit the number of digits I can put into one Entry module Tkinter?

from tkinter import *

root = Tk()

entrada = Entry(root) #Quero limitar para que nesse entry, possa colocar 
apenas 8 digitos

entrada.pack()

root.mainloop()

Thanks.

2 answers

1

This is an example code for a maximum of 5 digits:

from tkinter import *

def on_write(*args):
    s = var.get()
    if len(s) > 0:
        if not s[-1].isdigit(): # retirar ultimo caracter caso nao seja digito
            var.set(s[:-1])
        else: # aproveitar apenas os primeiros 5 chars
            var.set(s[:max_len])

root = Tk()
max_len = 5 # maximo num de caracteres
var = StringVar()
var.trace("w", on_write) # rastrear valor da variavel e executar funcao de validacao quando mudar

entrada = Entry(root, textvariable=var)
entrada.pack()
root.mainloop()

1

An example using the parameters validate and validatecommand widget Entry():

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Limitar quantidade de caracteres do entry()."""

from tkinter import *


def limitar_tamanho(p):
    if len(p) > 8:
        return False
    return True


root = Tk()

# Registrando a função que faz a validação.
vcmd = root.register(func=limitar_tamanho)

entrada = Entry(root, validate='key', validatecommand=(vcmd, '%P'))

entrada.pack()

root.mainloop()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.