最近,我发现条目小部件的验证选项非常有用(请参见this question)。我最近尝试编写一个验证命令来验证用户是否键入了十六进制代码或命名颜色。我写了这篇文章,它对十六进制代码很管用,偶尔也适用于颜色。它在每一个按键上都能运行。(validate=ALL
)
def checkColorValid(P):
global backgroundColor
if not P:
return True
if P.lower() in colors:
backgroundColor = P
return True
if P[0] == '#':
try:
if len(P) == 1:
return True
int(P[1:], 16)
if len(P) < 8:
backgroundColor = P
return True
else:
return False
except ValueError:
return False
for color in colors:
if color.startswith(P.lower()):
return True
colors
是所有有效命名颜色的列表。
验证代码是有效的,除非您试图键入一个命名的颜色,并开始反复键入同一个字符。一旦发生这种情况,验证似乎就停止工作了。它不再运行,直到你重新启动程序。在
验证代码可能返回}。也许添加一个最终的return语句会有所帮助。在
None
,而不是True
或{相关问题 更多 >
编程相关推荐