请利用Button、Textbox控件在Form中完成整数的加减乘除四则运算
时间: 2024-05-10 10:21:06 浏览: 14
以下是一个简单的示例代码:
```python
import tkinter as tk
class Calculator(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.create_widgets()
def create_widgets(self):
self.num1_entry = tk.Entry(self.master)
self.num1_entry.pack(side="left")
self.operation_label = tk.Label(self.master, text="+")
self.operation_label.pack(side="left")
self.num2_entry = tk.Entry(self.master)
self.num2_entry.pack(side="left")
self.calculate_button = tk.Button(self.master, text="=", command=self.calculate)
self.calculate_button.pack(side="left")
self.result_label = tk.Label(self.master, text="")
self.result_label.pack(side="left")
def calculate(self):
num1 = int(self.num1_entry.get())
num2 = int(self.num2_entry.get())
if self.operation_label["text"] == "+":
result = num1 + num2
elif self.operation_label["text"] == "-":
result = num1 - num2
elif self.operation_label["text"] == "*":
result = num1 * num2
elif self.operation_label["text"] == "/":
result = num1 / num2
self.result_label["text"] = str(result)
root = tk.Tk()
calculator = Calculator(master=root)
calculator.pack()
root.mainloop()
```
在这个示例中,我们创建了一个Calculator类,它继承自tkinter的Frame类。我们在create_widgets方法中创建了四个控件:两个Entry控件用于输入两个整数,一个Label控件用于显示运算符,一个Button控件用于执行计算,一个Label控件用于显示结果。
在calculate方法中,我们首先获取两个Entry控件中的整数值,然后根据运算符执行相应的计算。最后,我们将结果转换为字符串并显示在结果Label控件中。
您可以根据需要修改这个示例代码来实现更复杂的计算器功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)