Restricting the value in Tkinter Entry widget

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

    if you are dealing with locales that have a comma as decimal point:

    locale.setlocale(locale.LC_ALL,'de_DE.UTF-8') # German
    

    vcmd = (self.root.register(self.entry_numericonly), '%d', '%P')
    

    self.my_float_entry = tk.Entry(self.root, ... , validate='key', validatecommand=vcmd)
    

    def entry_numericonly(self, action, value_if_allowed):
        if(action == "1"):
            try:
                loc_float  = locale.atof(value_if_allowed)
                loc_float_format = locale.format("%f", loc_float)
                try:
                    loc_same_length = loc_float_format[:len(value_if_allowed)]
                    return value_if_allowed == loc_same_length
                except:
                    return False                    
            except:
                return False
        else:
            return True
    

提交回复
热议问题