Tkinter 回调 Traceback 错误中的异常。如何处理

这是一个使用 tkinter gui 添加 2 个数字的小型 Python 程序。如果文本字段中有一些输入,它运行良好。如果输入为空白或数字以外的字符,如何处理导致的错误。


from tkinter import *


root = Tk()



class addtwo:


    def evaluate(self, master, label, a, b):

        label.configure(text="The result is" + str(a+b))


    def __init__(self, master):

        frame = Frame(master, width=300, height=200)


        button1 = Button(master, text="Sum")

        input1 = Entry(master, text="Text1")

        input2 = Entry(master, text="Text2")

        label = Label(master, text="")




        button1.bind("<Button-1>", lambda event: self.evaluate(master, label,int(input1.get()),int(input2.get()) ))






        input1.pack()

        input2.pack()

        frame.focus()

        button1.pack()

        label.pack()

        frame.pack()



addtwo(root)

   root.mainloop()

错误:


Exception in Tkinter callback

Traceback (most recent call last):

  File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__

    return self.func(*args)

  File "/home/temporary/PycharmProjects/practise/addtwo.py", line 21, in <lambda>

    button1.bind("<Button-1>", lambda event: self.evaluate(master, label,int(input1.get()),int(input2.get()) ))

ValueError: invalid literal for int() with base 10: ''


慕容3067478
浏览 305回答 1
1回答

慕村225694

您可以使用try/except捕获错误并显示一些消息Label而不是结果。import tkinter as tkclass AddTwo:&nbsp; &nbsp; def __init__(self, master):&nbsp; &nbsp; &nbsp; &nbsp; frame = tk.Frame(master, width=300, height=200)&nbsp; &nbsp; &nbsp; &nbsp; self.input1 = tk.Entry(master, text="Text1")&nbsp; &nbsp; &nbsp; &nbsp; self.input2 = tk.Entry(master, text="Text2")&nbsp; &nbsp; &nbsp; &nbsp; button1 = tk.Button(master, text="Sum", command=self.evaluate)&nbsp; &nbsp; &nbsp; &nbsp; self.label = tk.Label(master, text="")&nbsp; &nbsp; &nbsp; &nbsp; self.input1.pack()&nbsp; &nbsp; &nbsp; &nbsp; self.input2.pack()&nbsp; &nbsp; &nbsp; &nbsp; button1.pack()&nbsp; &nbsp; &nbsp; &nbsp; self.label.pack()&nbsp; &nbsp; &nbsp; &nbsp; frame.pack()&nbsp; &nbsp; &nbsp; &nbsp; frame.focus()&nbsp; &nbsp; def evaluate(self):&nbsp; &nbsp; &nbsp; &nbsp; a_str = self.input1.get()&nbsp; &nbsp; &nbsp; &nbsp; b_str = self.input2.get()&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a = int(a_str)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b = int(b_str)&nbsp; &nbsp; &nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.label['text'] = "Wrong value(s) {} and/or {}".format(a_str, b_str)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; self.label['text'] = "The result is {}".format(a+b)# --- main ---root = tk.Tk()AddTwo(root)root.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python