因此,我有一些代码可用于验证条目小部件,以便只能输入整数值。我想达到相同的效果,但是除了整数值以外,两个整数值和浮点值都被排除在外。
from tkinter import *
root = Tk()
def testVal(inp,acttyp):
if acttyp == '1': #insert
if not inp.isdigit():
return False
return True
entry = Entry(root, validate="key")
entry['validatecommand'] = (entry.register(testVal),'%P','%d')
entry.pack()
root.mainloop()
答案 0 :(得分:1)
您只需在输入文本上调用float()
即可确定它是整数还是浮点数:
from tkinter import *
def validate_entry(inp):
try:
float(inp)
except:
return False
return True
root = Tk()
Entry(root, validate='key', vcmd=(root.register(validate_entry), '%P')).pack()
root.mainloop()
答案 1 :(得分:0)
我的基本函数 isfloat() 用于 Tkinter 条目小部件浮动验证和限制(-90.00 到 90.00)
from tkinter import *
def isfloat(P):
if (P == "" or P == "-"):
return True
else:
c=0
i,j,k,l=1,1,1,1
for x in P:
if(i==2):
if(j==2):
if(k==1):
if(x=='1' or x=='2' or x=='3' or x=='4' or x=='5' or x=='6' or x=='7' or
x=='8' or x=='9' or x=='0' or x=='.'):
c+=1
if(x=='.'):k=2
elif(k==2):
if(x=='1' or x=='2' or x=='3' or x=='4' or x=='5' or x=='6' or x=='7' or
x=='8' or x=='9' or x=='0'):
c+=1
elif(j==1):
if(l==1):
if(x=='1' or x=='2' or x=='3' or x=='4' or x=='5' or x=='6' or x=='7' or
x=='8' or x=='9' or x=='0' or x=='.'):
c+=1
j=2
if(x=='.'):k=2
elif(l==2):
if(x=='1' or x=='2' or x=='3' or x=='4' or x=='5' or x=='6' or x=='7' or
x=='8' or x=='9' or x=='0'):
c+=1
j=2
elif(i==1):
if(x=='1' or x=='2' or x=='3' or x=='4' or x=='5' or x=='6' or x=='7' or
x=='8' or x=='9' or x=='0' or x=='-'):
c+=1
i=2
if(x=='-'):l=2
else:
return False
else:
return False
#For latitude calculation, 'P' is the number, '-90.0' is the from, '-90.0' is the to
if(c==len(P) and float(P)<=90.0 and float(P)>=-90.0):
return True
else:
return False
def prt():
if(col[0].get()!=""):print(float(col[0].get()), "\t", type(float(col[0].get())))
else:False
setup=Tk()
setup.geometry("200x200")
col,d=[],[]
col.append(StringVar())
d.append(Entry(setup, textvariable=col[0], width=15, validate='all', validatecommand=((setup.register(isfloat)), '%P')))
d[0].grid(row=0,column=0)
Button(setup,text="Print",command=prt).grid(row=1,column=0)
setup.mainloop()