按下按钮的Try-except语句无效



我使用tKinter库用Python编写了一段简单的代码。我想使用一个带有tryexcept ValueError的简单函数来检查用户输入是否是一个数字。出于某种原因,它只显示当输入不是数字时应该打印的文本。按下按钮后应该出现的消息存储在feedback变量中。所以问题是:我如何使它不给出";这不是一个数字";默认情况下在屏幕上打印,但按下保存按钮后会显示一个带有正确文本的空屏幕。

def number_input():
root=Tk()
root.geometry(400x400)

rounds=Entry(root)

feedback=Label(root, text='')
feedback.place(relx=0.5, rely=0.8, anchor=CENTER)

save=Button(root, height=1, width=10, text='save', command=number())
save.place(relx=0.5, rely=0.72, anchor=CENTER)

这是tryexcept部分的功能:

def number():
try:
int(rounds.get())
feedback.config(text='This is a number')
except ValueError:
feedback.config(text='This is not a number')

您的代码:

save = Button(..., command=number())

它调用number函数,并将命令设置为该函数的结果None。你想做的是:

save = Button(..., command=number)

它将函数传递给tkinter,这样它就可以在您按下按钮时调用它。

最新更新