1 回答
TA贡献1880条经验 获得超4个赞
您可以使用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()
添加回答
举报