[英]Python ttk entry validation with hex value
I've been thinking in a way to validate a ttk Entry box for a Hex value of 4 characters. 我一直在想一种验证ttk Entry框的方法,其中Hex值为4个字符。
I came to a solution but I'm not sure if there is a more correct/pythonist way to do it. 我找到了一个解决方案,但我不确定是否有更正确/蟒蛇的方式来做到这一点。
This is the Entry declaration: 这是条目声明:
vcdmCheckSum = (self.register(self.OnValidateCheckSum), '%P', '%d')
self.tlCheckSumEntry = Entry(self, validate="key", validatecommand=vcdmCheckSum, width=10)
self.tlCheckSumEntry.grid(row=self.rowOptions2, column=self.columnOptions1, sticky=tk.W+tk.N, padx=5, pady=5)
And this is my OnValidateCheckSum function: 这是我的OnValidateCheckSum函数:
def OnValidateCheckSum(self, P, d):
# If you are not writting but deleting
if d <> '1':
return True
try:
return (len(P) < 5) and (int(P, 16) <= int('FFFF', 16))
except:
return False
The tricky thing is that if I use int(P, 16) without checking the max value and start writing a 0 It wont work since int('0') is false as int('0', 16). 棘手的是,如果我使用int(P,16)而不检查最大值并开始写0它不会工作,因为int('0')假为int('0',16)。
So, once again. 所以,再一次。 Is that the way to do it?
那是这样做的吗? Is there a better or more "pythonic" way to do so?
有更好或更“pythonic”的方式吗?
Assuming there are no special characters in the string (like $ or 0x): 假设字符串中没有特殊字符(如$或0x):
def OnValidateCheckSum(self, P, d):
valid_hex_char = lambda c: c in 'abcdef0123456789'
return (len(P) < 5) and (all(valid_hex_char(z) for z in P.lower()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.