Restricting the value in Tkinter Entry widget

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

    I had to deal with an initial insert case as well. This is what I have ended up with:

        def _checkNumberOnly(self, action, value_if_allowed):
            if action != '1':
               return True
            try:
                return value_if_allowed.isnumeric()
            except ValueError:
               return False
    
        vcmd = (self.register(self._checkNumberOnly), '%d', '%P')
            self.port = ttk.Entry(self, width=35, validate='key', validatecommand=vcmd)
    

    Therefore it validates for the following:

        self.port.insert(0, '6379')
    

    I'm not sure that the catch is needed, due to isnumeric() not stating it raises an exception.

提交回复
热议问题