编写程序,利用tkinter GUI 设计加法计算,将操作数据填入输入框后,单击“加法”按钮将算式和结果填入下方的结果文本框中,单击“清空”按钮将清空输入框和结果文本框
时间: 2024-02-16 10:59:54 浏览: 86
好的,下面是代码实现,需要安装 tkinter 库:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("加法计算器")
# 输入框
self.num1_label = tk.Label(master, text="第一个数:")
self.num1_label.grid(row=0, column=0, padx=10, pady=10)
self.num1_entry = tk.Entry(master)
self.num1_entry.grid(row=0, column=1, padx=10, pady=10)
self.num2_label = tk.Label(master, text="第二个数:")
self.num2_label.grid(row=1, column=0, padx=10, pady=10)
self.num2_entry = tk.Entry(master)
self.num2_entry.grid(row=1, column=1, padx=10, pady=10)
# 结果文本框
self.result_label = tk.Label(master, text="计算结果:")
self.result_label.grid(row=2, column=0, padx=10, pady=10)
self.result_text = tk.Text(master, height=1)
self.result_text.grid(row=2, column=1, padx=10, pady=10)
# 加法按钮
self.add_button = tk.Button(master, text="加法", command=self.add)
self.add_button.grid(row=3, column=0, padx=10, pady=10)
# 清空按钮
self.clear_button = tk.Button(master, text="清空", command=self.clear)
self.clear_button.grid(row=3, column=1, padx=10, pady=10)
def add(self):
try:
num1 = float(self.num1_entry.get())
num2 = float(self.num2_entry.get())
result = num1 + num2
self.result_text.delete(1.0, tk.END)
self.result_text.insert(tk.END, str(num1) + " + " + str(num2) + " = " + str(result))
except ValueError:
self.result_text.delete(1.0, tk.END)
self.result_text.insert(tk.END, "请输入正确的数字!")
def clear(self):
self.num1_entry.delete(0, tk.END)
self.num2_entry.delete(0, tk.END)
self.result_text.delete(1.0, tk.END)
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
运行后会弹出一个窗口,可以输入两个数,点击“加法”按钮进行计算,点击“清空”按钮清空输入框和结果文本框。
阅读全文