写可视化计算器
时间: 2023-08-13 21:07:29 浏览: 162
可视化计算器
好的,我可以用Python和Tkinter库来写一个简单的可视化计算器。以下是代码示例:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
# Create the calculator display
self.display = tk.Entry(master, width=30)
self.display.grid(row=0, column=0, columnspan=4)
# Create the calculator buttons
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("C", 4, 2)
self.create_button("+", 4, 3)
self.create_button("=", 5, 0, columnspan=4)
def create_button(self, text, row, col, rowspan=1, columnspan=1):
button = tk.Button(self.master, text=text, width=7, height=3, command=lambda: self.button_click(text))
button.grid(row=row, column=col, rowspan=rowspan, columnspan=columnspan)
def button_click(self, text):
if text == "C":
self.display.delete(0, tk.END)
elif text == "=":
try:
result = eval(self.display.get())
self.display.delete(0, tk.END)
self.display.insert(0, result)
except:
self.display.delete(0, tk.END)
self.display.insert(0, "Error")
else:
self.display.insert(tk.END, text)
# Create the main window
root = tk.Tk()
root.title("Calculator")
# Create the calculator
calculator = Calculator(root)
# Start the main loop
root.mainloop()
```
这个代码创建了一个简单的可视化计算器,可以处理加减乘除等基本运算。你可以根据需要进行修改和扩展。
阅读全文