基于Tkinter的双输入框计算器返回空白结果问题求助
解决Tkinter计算器弹出空白窗口及变量为空的问题
问题根源
- 变量初始化时机错误:你在窗口刚创建、输入框还未接收用户输入时,就执行了
num1=e1.get()和num2=e2.get(),导致这两个变量始终是空字符串。 - 未转换数据类型:Entry组件获取的内容是字符串,直接用于数学运算会引发错误(减法/乘法/除法直接报错,加法仅做字符串拼接)。
修复方案
- 将获取输入框内容的操作移到每个运算函数内部,确保每次点击按钮时读取的是用户当前输入的值。
- 将获取到的字符串转换为数值类型(
float或int)后再执行运算。 - 新增异常处理,避免用户输入非数字内容或除数为0导致程序崩溃。
修复后的完整代码
from tkinter import * from tkinter.messagebox import * def addition(): try: num1 = float(e1.get()) num2 = float(e2.get()) showinfo("计算结果", f"{num1} + {num2} = {num1 + num2}") except ValueError: showerror("错误", "请输入有效的数字") def soust(): try: num1 = float(e1.get()) num2 = float(e2.get()) showinfo("计算结果", f"{num1} - {num2} = {num1 - num2}") except ValueError: showerror("错误", "请输入有效的数字") def multi(): try: num1 = float(e1.get()) num2 = float(e2.get()) showinfo("计算结果", f"{num1} * {num2} = {num1 * num2}") except ValueError: showerror("错误", "请输入有效的数字") def divi(): try: num1 = float(e1.get()) num2 = float(e2.get()) if num2 == 0: showerror("错误", "除数不能为0") return showinfo("计算结果", f"{num1} / {num2} = {num1 / num2}") except ValueError: showerror("错误", "请输入有效的数字") def annuler(): e1.delete(0, END) e2.delete(0, END) root = Tk() root.title("Exemple 6") nombre1 = Label(root, text="nombre1", background="green") nombre1.pack() e1 = Entry(root) e1.pack() nombre2 = Label(root, text="nombre2", background="green") nombre2.pack() e2 = Entry(root) e2.pack() button1 = Button(root, text=" + ", command=addition, activebackground="red") button1.pack(side=LEFT) button2 = Button(root, text=" - ", command=soust, activebackground="red") button2.pack(side=LEFT) button3 = Button(root, text=" * ", command=multi, activebackground="red") button3.pack(side=LEFT) button4 = Button(root, text=" / ", command=divi, activebackground="red") button4.pack(side=LEFT) button5 = Button(root, text=" C ", command=annuler, activebackground="red") button5.pack(side=LEFT) root.mainloop()
额外说明
- 结果弹窗新增了完整运算表达式,展示更直观。
- 针对除法场景单独处理了除数为0的异常,提升程序健壮性。
内容的提问来源于stack exchange,提问作者Mohamed Ayoub
相关产品推荐
相关产品推荐

