python简易计算器窗口
时间: 2023-07-08 07:46:28 浏览: 94
python简易计算器
好的,以下是一个简单的 Python 计算器窗口的示例代码,你可以参考它进行修改和扩展:
```python
from tkinter import *
class Calculator:
def __init__(self, master):
self.master = master
master.title("简易计算器")
self.screen = Text(master, state='disabled', width=30, height=3,background="white", foreground="black")
self.screen.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
self.screen.configure(state='normal')
# 创建按钮并放置在网格中
b1 = self.create_button(7)
b2 = self.create_button(8)
b3 = self.create_button(9)
b4 = self.create_button(u"\u232B",None)
b5 = self.create_button(4)
b6 = self.create_button(5)
b7 = self.create_button(6)
b8 = self.create_button(u"\u00F7")
b9 = self.create_button(1)
b10 = self.create_button(2)
b11 = self.create_button(3)
b12 = self.create_button('*')
b13 = self.create_button('.')
b14 = self.create_button(0)
b15 = self.create_button('+')
b16 = self.create_button('-')
b17 = self.create_button('=',None, 34)
# 存储按钮在列表中,以便于更改按钮颜色
self.buttons = [b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17]
# 创建 Clear 按钮并放置在网格中
clear_button = Button(master, text="Clear", width=14, height=2, command=self.clear)
clear_button.grid(row=1, column=3, padx=5, pady=5)
def create_button(self, val, write=True, width=7):
# 创建按钮的函数
return Button(self.master, text=val, width=width, command=lambda: self.click(val,write))
def click(self, text, write):
# 处理单击事件,将文本插入显示屏
if write == None:
# 处理计算器中的特殊按键
if text == '=' and self.screen.get('1.0', END) != '':
# 尝试计算表达式字符串
try:
result = eval(self.screen.get('1.0', END))
self.clear()
self.screen.insert(END, result)
except:
self.clear()
self.screen.insert(END, '错误')
elif text == u"\u232B":
# 处理退格键
current = self.screen.get('1.0', END)
self.clear()
self.screen.insert(END, current[:-2])
else:
# 处理数字和运算符
self.screen.insert(END, text)
def clear(self):
# 清空显示屏
self.screen.configure(state='normal')
self.screen.delete('1.0', END)
root = Tk()
my_gui = Calculator(root)
root.mainloop()
```
这个简易计算器窗口使用 Tkinter 模块创建,包含了数字、运算符和特殊按键。你可以通过修改按钮的标签和单击事件来扩展它的功能。
阅读全文