Restricting the value in Tkinter Entry widget

前端 未结 6 2054
盖世英雄少女心
盖世英雄少女心 2020-11-28 14:16

I need to restrict the values in the Entry widget to numbers only. The way I implemented is:

import numpy as np
from Tkinter import *;
import tkMessageBox;

         


        
6条回答
  •  一整个雨季
    2020-11-28 14:51

    I realize this is quite late for an answer but feel that I can give a lot simpler answer to this... it is really quite simple once you understand how it works.

    Use the validating feature that comes with the Entry widget.

    Lets assume self is a widget:

    vcmd = (self.register(self.callback))
    
    w = Entry(self, validate='all', validatecommand=(vcmd, '%P')) 
    w.pack()
    
    def callback(self, P):
        if str.isdigit(P) or P == "":
            return True
        else:
            return False
    

    You don't need to include all of the substitution codes: ('%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'), only the ones you'll use are necessary.

    The Entry widget returns a string so you will have to somehow extract any digits in order to separate them from other characters. The easiest way to do this is to use str.isdigit(). This is a handy little tool built right into python's libraries and needs no extra importing and it will identify any numerics (digits) that it finds from the string that the Entry widget returns.

    The or P == "" part of the if statement allows you to delete your entire entry, without it, you would not be able to delete the last (1st in entry box) digit due to '%P' returning an empty value and causing your callback to return False. I won't go into detail why here.

    validate='all' allows the callback to evaluate the value of P as you focusin, focusout or on any key stroke changing the contents in the widget and therefore you don't leave any holes for stray characters to be mistakenly entered.

    In all, to make things simple. If your callback returns True it will allow data to be entered. If the callback returns 'False` it will essentially 'ignore' keyboard input.

    Check out these two references. They explain what each substitution code means and how to implement them.

    http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html http://stupidpythonideas.blogspot.ca/2013/12/tkinter-validation.html

    EDIT: This will only take care of what is allowed in the box. You can, however, inside the callback, add whatever value P has to any variable you wish.

提交回复
热议问题