python - tkinter 条目的意外输出
问题描述
我的代码打算验证一个条目框。在我输入一个0
值之前它工作正常。之后验证不再起作用。
有人对正在发生的事情有解释吗?
我的代码:
from tkinter import *
root = Tk()
def correct(inp):
if (len(inp) <= 1) and (inp.isdigit()):
if ((int(inp) > 0) and (int(inp) < 10)):
if (inp != '0'):
return True
elif inp is "":
return True
else:
return False
e = Entry(root)
e.place(x = 50, y = 50)
reg = root.register(correct)
e.config(validate = "key", validatecommand = (reg, "%P"))
root.mainloop()
解决方案
验证您的输入在 0-9 之间时出错。inp
在验证它不是空之后也将其视为 int string
!
错误似乎是如果输入在范围内,而不是零,则返回 True,但如果为 0,则没有任何反应,因此此函数需要返回布尔值。
if ((int(inp) > 0) and (int(inp) < 10)): #within the range
if (inp != '0'): # if not a zero
return True # return true
# there is no else statement, no return if inp is 0
工作代码:
from tkinter import *
root = Tk()
def correct(inp):
if not inp.strip():
return True
if len(inp) == 1 and inp.isdigit() and 0 <= int(inp) < 10:
if (int(inp) != 0):
print('Not a zero')
return True
else:
print('This is a zero')
return True
return False
e = Entry(root)
e.place(x = 50, y = 50)
reg = root.register(correct)
e.config(validate = "key", validatecommand = (reg, "%P"))
root.mainloop()
推荐阅读
- javascript - 如何在 lightgallery onCloseAfter.lg 方法中调用 js 函数?
- encryption - 密码反馈模式:s 位大小混淆
- xamarin.forms - 带有圆形中央按钮的 Xamarin Forms 导航栏
- python - 是否有一种可接受的 Pythonic 方式将基类部分与子类对象分离?
- django - 如果在 django rest 框架中不存在,则自动在反向外部表中创建项目
- python-3.x - Django NoReverseMatch:找不到“条目”的反向。“登录”不是有效的视图函数或模式
- liquibase - liquibase 中的约束
- java - 无法启动 logbox,因为 react 无法在 Google Pixel 8.0 中创建根视图
- python - 使用while退出for循环
- snowflake-cloud-data-platform - 如何在存储过程中实现执行流程并获得表输出