Restricting the value in Tkinter Entry widget

前端 未结 6 2060
盖世英雄少女心
盖世英雄少女心 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:55

    The answer is almost perfect, just a little addition to allow for deleting the whole string. The check for floats should be done only when inserting text

    def validate_float(self, action, index, value_if_allowed,
        prior_value, text, validation_type, trigger_type, widget_name):
        # action=1 -> insert
        if(action=='1'):
            if text in '0123456789.-+':
                try:
                    float(value_if_allowed)
                    return True
                except ValueError:
                    return False
            else:
                return False
        else:
            return True
    

提交回复
热议问题