5. 自主编程:计算器,使用恰当的组件和容器,加完成软件界面设计
时间: 2024-03-06 11:48:23 浏览: 71
好的,我可以帮您编写一个基本的计算器程序。由于我是一个语言模型AI,无法直接为您提供UI设计,需要您自己设计界面。以下是一个简单的计算器程序代码示例,您可以将其添加到自己的UI中:
```python
from tkinter import *
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
# 创建文本框
self.display = Entry(master, width=25, font=('Arial', 16))
self.display.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
# 创建计算器按钮
self.create_button('7', 1, 0)
self.create_button('8', 1, 1)
self.create_button('9', 1, 2)
self.create_button('/', 1, 3)
self.create_button('4', 2, 0)
self.create_button('5', 2, 1)
self.create_button('6', 2, 2)
self.create_button('*', 2, 3)
self.create_button('1', 3, 0)
self.create_button('2', 3, 1)
self.create_button('3', 3, 2)
self.create_button('-', 3, 3)
self.create_button('0', 4, 0)
self.create_button('.', 4, 1)
self.create_button('=', 4, 2)
self.create_button('+', 4, 3)
self.create_button('C', 5, 0)
self.create_button('(', 5, 1)
self.create_button(')', 5, 2)
self.create_button('Quit', 5, 3)
def create_button(self, text, row, column):
button = Button(self.master, text=text, width=5, font=('Arial', 16), command=lambda:self.button_click(text))
button.grid(row=row, column=column, padx=5, pady=5)
def button_click(self, text):
if text == '=':
result = eval(self.display.get())
self.display.delete(0, END)
self.display.insert(END, str(result))
elif text == 'C':
self.display.delete(0, END)
elif text == 'Quit':
self.master.destroy()
else:
self.display.insert(END, text)
root = Tk()
my_calculator = Calculator(root)
root.mainloop()
```
这是一个基本的四则运算计算器程序,您可以根据自己的需要进行修改和完善。希望对您有帮助!
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)