Python 如何在tkinter中验证输入字段
我只需要在输入字段中打印数字和符号“.”。但运行此代码后,我只能键入数字或符号“.”(我尝试键入“2.45”,但point不会在“2”之后键入。如果我尝试键入“.45”,则“.45”不会在“.”之后键入)。我如何解决这个问题Python 如何在tkinter中验证输入字段,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我只需要在输入字段中打印数字和符号“.”。但运行此代码后,我只能键入数字或符号“.”(我尝试键入“2.45”,但point不会在“2”之后键入。如果我尝试键入“.45”,则“.45”不会在“.”之后键入)。我如何解决这个问题 from tkinter import * root = Tk() entry = Entry(width=10) entry.pack() def correct(inp): if inp.isdigit(): return True
from tkinter import *
root = Tk()
entry = Entry(width=10)
entry.pack()
def correct(inp):
if inp.isdigit():
return True
elif inp == ".":
return True
elif inp == "":
return True
else:
return False
reg = root.register(correct)
entry.config(validate='key', validatecommand = (reg, '%P'))
root.mainloop()
您的验证函数没有写错…我认为这将是一种更简单的方法来完成您想要的:
import tkinter as tk
root = tk.Tk()
entry = tk.Entry(width=10)
entry.pack()
def correct(inp):
""" Determine if inp value is a valid floating point number. """
try:
float(inp)
except ValueError:
return inp == '' # Consider empty string valid.
else:
return True
reg = root.register(correct)
entry.config(validate='key', validatecommand=(reg, '%P'))
root.mainloop()
您的验证函数没有写错…我认为这将是一种更简单的方法来完成您想要的:
import tkinter as tk
root = tk.Tk()
entry = tk.Entry(width=10)
entry.pack()
def correct(inp):
""" Determine if inp value is a valid floating point number. """
try:
float(inp)
except ValueError:
return inp == '' # Consider empty string valid.
else:
return True
reg = root.register(correct)
entry.config(validate='key', validatecommand=(reg, '%P'))
root.mainloop()
非常感谢您的回答。它几乎可以正常工作。唯一的问题是我不能从我的输入字段中删除最后一个数字。如果你想接受空字符串,你需要把它作为一个特殊情况来处理。我已经修改了我的答案,非常感谢你们的回答。它几乎可以正常工作。唯一的问题是我不能从我的输入字段中删除最后一个数字。如果你想接受空字符串,你需要把它作为一个特殊情况来处理。为了做到这一点,我修改了我的答案。