首页 > 解决方案 > 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()

标签: pythondebuggingtkinter

解决方案


验证您的输入在 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()

推荐阅读