编写程序,利用tkinter GUI 设计加法计算,将操作数据填入输入框后,单击“加法”按钮将算式和结果填入下方的结果文本框中,单击“清空”按钮将清空输入框和结果文本框
时间: 2024-02-15 20:05:58 浏览: 20
好的,以下是代码实现:
```python
import tkinter as tk
def add():
try:
num1 = float(entry1.get())
num2 = float(entry2.get())
result = num1 + num2
label_result.config(text=f"{num1} + {num2} = {result}")
except ValueError:
label_result.config(text="请输入数字!")
def clear():
entry1.delete(0, tk.END)
entry2.delete(0, tk.END)
label_result.config(text="")
root = tk.Tk()
root.title("加法计算器")
label1 = tk.Label(root, text="加数1:")
label1.grid(row=0, column=0)
entry1 = tk.Entry(root)
entry1.grid(row=0, column=1)
label2 = tk.Label(root, text="加数2:")
label2.grid(row=1, column=0)
entry2 = tk.Entry(root)
entry2.grid(row=1, column=1)
button_add = tk.Button(root, text="加法", command=add)
button_add.grid(row=2, column=0)
button_clear = tk.Button(root, text="清空", command=clear)
button_clear.grid(row=2, column=1)
label_result = tk.Label(root)
label_result.grid(row=3, column=0, columnspan=2)
root.mainloop()
```
运行代码后,会弹出一个窗口,界面上有两个输入框和两个按钮,输入两个数后点击“加法”按钮即可得到结果,点击“清空”按钮可以清空输入框和结果文本框。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)