这是一个小型的python程序,使用tkinter gui加2个数字。如果文本字段中有一些输入,它运行良好。如果输入为空白或数字以外的字符,如何处理错误。
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: ''
答案 0 :(得分:1)
您可以使用try/except
来捕获错误并在Label
中显示一些消息而不是结果。
import tkinter as tk
class AddTwo:
def __init__(self, master):
frame = tk.Frame(master, width=300, height=200)
self.input1 = tk.Entry(master, text="Text1")
self.input2 = tk.Entry(master, text="Text2")
button1 = tk.Button(master, text="Sum", command=self.evaluate)
self.label = tk.Label(master, text="")
self.input1.pack()
self.input2.pack()
button1.pack()
self.label.pack()
frame.pack()
frame.focus()
def evaluate(self):
a_str = self.input1.get()
b_str = self.input2.get()
try:
a = int(a_str)
b = int(b_str)
except ValueError:
self.label['text'] = "Wrong value(s) {} and/or {}".format(a_str, b_str)
return
self.label['text'] = "The result is {}".format(a+b)
# --- main ---
root = tk.Tk()
AddTwo(root)
root.mainloop()