python简易计算器窗口
时间: 2023-07-08 08:46:20 浏览: 49
Python简易计算器制作方法代码详解
5星 · 资源好评率100%
好的,下面是一个简易的Python计算器窗口的代码示例:
```python
from tkinter import *
def add_to_input(num):
input_field.insert(END, num)
def calculate():
try:
result = eval(input_field.get())
input_field.delete(0, END)
input_field.insert(END, result)
except:
input_field.delete(0, END)
input_field.insert(END, "Error")
def clear_input():
input_field.delete(0, END)
# 创建窗口
window = Tk()
window.title("简易计算器")
# 创建输入框
input_field = Entry(window, font=('Arial', 16))
input_field.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
# 创建数字按钮
button_1 = Button(window, text="1", font=('Arial', 16), command=lambda:add_to_input(1))
button_1.grid(row=1, column=0, padx=5, pady=5)
button_2 = Button(window, text="2", font=('Arial', 16), command=lambda:add_to_input(2))
button_2.grid(row=1, column=1, padx=5, pady=5)
button_3 = Button(window, text="3", font=('Arial', 16), command=lambda:add_to_input(3))
button_3.grid(row=1, column=2, padx=5, pady=5)
button_4 = Button(window, text="4", font=('Arial', 16), command=lambda:add_to_input(4))
button_4.grid(row=2, column=0, padx=5, pady=5)
button_5 = Button(window, text="5", font=('Arial', 16), command=lambda:add_to_input(5))
button_5.grid(row=2, column=1, padx=5, pady=5)
button_6 = Button(window, text="6", font=('Arial', 16), command=lambda:add_to_input(6))
button_6.grid(row=2, column=2, padx=5, pady=5)
button_7 = Button(window, text="7", font=('Arial', 16), command=lambda:add_to_input(7))
button_7.grid(row=3, column=0, padx=5, pady=5)
button_8 = Button(window, text="8", font=('Arial', 16), command=lambda:add_to_input(8))
button_8.grid(row=3, column=1, padx=5, pady=5)
button_9 = Button(window, text="9", font=('Arial', 16), command=lambda:add_to_input(9))
button_9.grid(row=3, column=2, padx=5, pady=5)
button_0 = Button(window, text="0", font=('Arial', 16), command=lambda:add_to_input(0))
button_0.grid(row=4, column=0, padx=5, pady=5)
# 创建运算符按钮
button_add = Button(window, text="+", font=('Arial', 16), command=lambda:add_to_input("+"))
button_add.grid(row=1, column=3, padx=5, pady=5)
button_subtract = Button(window, text="-", font=('Arial', 16), command=lambda:add_to_input("-"))
button_subtract.grid(row=2, column=3, padx=5, pady=5)
button_multiply = Button(window, text="*", font=('Arial', 16), command=lambda:add_to_input("*"))
button_multiply.grid(row=3, column=3, padx=5, pady=5)
button_divide = Button(window, text="/", font=('Arial', 16), command=lambda:add_to_input("/"))
button_divide.grid(row=4, column=3, padx=5, pady=5)
button_equal = Button(window, text="=", font=('Arial', 16), command=calculate)
button_equal.grid(row=4, column=2, padx=5, pady=5)
button_clear = Button(window, text="C", font=('Arial', 16), command=clear_input)
button_clear.grid(row=4, column=1, padx=5, pady=5)
# 运行窗口
window.mainloop()
```
该程序使用了Tkinter模块,可以创建一个简单的窗口界面,包含数字和运算符按钮,并且可以进行基本的数学运算。
阅读全文