Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 限制Tkinter条目小部件中的值:为什么可以';我不能删除第一个字符吗?_Python_Validation_Tkinter - Fatal编程技术网

Python 限制Tkinter条目小部件中的值:为什么可以';我不能删除第一个字符吗?

Python 限制Tkinter条目小部件中的值:为什么可以';我不能删除第一个字符吗?,python,validation,tkinter,Python,Validation,Tkinter,本例成功地只允许输入数字,但在输入第一个字符后,不允许删除它。为什么会这样 import Tkinter as tk class window2: def __init__(self, master1): self.panel2 = tk.Frame(master1) self.panel2.grid() self.button2 = tk.Button(self.panel2, text = "Quit", command = self

本例成功地只允许输入数字,但在输入第一个字符后,不允许删除它。为什么会这样

import Tkinter as tk

class window2:
    def __init__(self, master1):
        self.panel2 = tk.Frame(master1)
        self.panel2.grid()
        self.button2 = tk.Button(self.panel2, text = "Quit", command = self.panel2.quit)
        self.button2.grid()
        vcmd = (master1.register(self.validate),
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.text1 = tk.Entry(self.panel2, validate = 'key', validatecommand = vcmd)
        self.text1.grid()
        self.text1.focus()

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

root1 = tk.Tk()
window2(root1)
root1.mainloop()

因为删除字符会给您留下
,根据您的规则,这是不可接受的条目:

>>> "" in '0123456789.-+'
True
但是

>>浮点(“”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
浮动(“”)
ValueError:无法将字符串转换为浮点:
>>> float("")
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    float("")
ValueError: could not convert string to float: