用tkinter实现一个简单计算器,支持小数点,多次运算
时间: 2023-07-20 14:05:18 浏览: 109
python使用tkinter实现简单计算器
好的,以下是一个简单的计算器演示程序:
```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="blue")
self.screen.grid(row=0,column=0,columnspan=4,padx=5,pady=5)
self.equation = ''
# 创建按钮
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)
# 将按钮添加到列表中
buttons = [b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17]
# 将按钮添加到网格中
count = 0
for row in range(1, 5):
for column in range(4):
buttons[count].grid(row=row, column=column)
count += 1
buttons[16].grid(row=5, column=0, columnspan=4)
def create_button(self, val, write=True, width=7):
return Button(self.master, text=val, command=lambda:self.click(val,write), width=width, height=2, bg="white", fg="black")
def click(self, text, write):
if write == None:
if text == '=' and self.equation:
try:
result = str(eval(self.equation))
self.clear_screen()
self.insert_screen(result, newline=True)
except:
self.clear_screen()
self.insert_screen("Error!", newline=True)
elif text == u"\u232B":
self.clear_screen()
else:
self.insert_screen(text)
def clear_screen(self):
self.equation = ''
self.screen.configure(state='normal')
self.screen.delete('1.0', END)
def insert_screen(self, value, newline=False):
self.screen.configure(state='normal')
self.screen.insert(END, value)
self.equation += str(value)
self.screen.configure(state='disabled')
root = Tk()
gui = Calculator(root)
root.mainloop()
```
这个程序使用了Tkinter库来创建一个简单的计算器界面,支持小数点和多次运算。你可以按照自己的需要进行修改和扩展。
阅读全文