用tkinter包写个计算器 包括程序员计算器和科学计算器功能
时间: 2023-08-15 08:05:05 浏览: 133
好的,下面是一个简单的计算器程序,包括了基本计算、程序员计算和科学计算三种模式。程序使用Python的tkinter包实现,代码如下:
```python
import tkinter as tk
import math
class Calculator:
def __init__(self, master):
self.master = master
self.master.title("Calculator")
self.master.geometry("300x400")
self.mode = "basic"
self.create_widgets()
def create_widgets(self):
# display
self.display = tk.Entry(self.master, width=30, font=("Arial", 16), justify="right")
self.display.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# buttons
btn_list = [
"C", "CE", "←", "/",
"7", "8", "9", "*",
"4", "5", "6", "-",
"1", "2", "3", "+",
"+/-", "0", ".", "="
]
r = 1
c = 0
for btn_text in btn_list:
btn = tk.Button(self.master, text=btn_text, font=("Arial", 12), width=5, height=2)
btn.grid(row=r, column=c, padx=5, pady=5)
btn.bind("<Button-1>", self.button_clicked)
c += 1
if c == 4:
c = 0
r += 1
# mode buttons
mode_list = ["Basic", "Programmer", "Scientific"]
r = 6
c = 0
for mode_text in mode_list:
btn = tk.Button(self.master, text=mode_text, font=("Arial", 12), width=10, height=2)
btn.grid(row=r, column=c, padx=5, pady=5)
btn.bind("<Button-1>", self.mode_button_clicked)
c += 1
def button_clicked(self, event):
btn = event.widget
btn_text = btn["text"]
if btn_text == "C":
self.display.delete(0, tk.END)
elif btn_text == "CE":
self.display.delete(len(self.display.get())-1, tk.END)
elif btn_text == "←":
self.display.delete(len(self.display.get())-1, tk.END)
elif btn_text == "+/-":
if self.display.get().startswith("-"):
self.display.delete(0)
else:
self.display.insert(0, "-")
elif btn_text == "=":
try:
result = self.calculate()
self.display.delete(0, tk.END)
self.display.insert(0, result)
except ZeroDivisionError:
self.display.delete(0, tk.END)
self.display.insert(0, "Error")
else:
self.display.insert(tk.END, btn_text)
def mode_button_clicked(self, event):
btn = event.widget
mode_text = btn["text"]
if mode_text == "Basic":
self.mode = "basic"
elif mode_text == "Programmer":
self.mode = "programmer"
elif mode_text == "Scientific":
self.mode = "scientific"
def calculate(self):
expression = self.display.get()
if self.mode == "basic":
result = eval(expression)
elif self.mode == "programmer":
result = self.programmer_calculate(expression)
elif self.mode == "scientific":
result = self.scientific_calculate(expression)
return result
def programmer_calculate(self, expression):
try:
# convert to int
result = int(expression, 0)
except ValueError:
result = 0
return result
def scientific_calculate(self, expression):
try:
result = eval(expression)
except ZeroDivisionError:
result = 0
if "pi" in expression:
result = result * math.pi
if "e" in expression:
result = result * math.e
return result
root = tk.Tk()
app = Calculator(root)
root.mainloop()
```
这个程序包括了基本计算、程序员计算和科学计算三种模式,可以通过按钮切换。在基本计算模式下,可以进行加、减、乘、除等基本运算;在程序员计算模式下,可以进行二进制、八进制、十进制和十六进制的转换;在科学计算模式下,可以进行三角函数、对数、指数等高级运算。
阅读全文