制作一个计算器的GUI程序。计算器包括数字按键、运算符按键、清空和退格按键等。当用户输入一个算式时,程序会进行计算并在显示窗口中显示结果。
时间: 2024-02-13 19:03:12 浏览: 54
一个用GUI编的计算器-计算器.zip
好的,这是一个简单的Python代码实现:
```python
import tkinter as tk
# 创建窗口
window = tk.Tk()
window.title("计算器")
window.geometry("300x400")
# 定义计算器显示窗口
result = tk.StringVar()
result.set("0")
display = tk.Label(window, textvariable=result, font=("Arial", 20), width=15, height=2)
display.pack()
# 定义按钮点击事件
def click(num):
current = result.get()
if current == "0":
current = ""
result.set(current + str(num))
def clear():
result.set("0")
def backspace():
current = result.get()
if len(current) > 1:
result.set(current[:-1])
else:
result.set("0")
def calculate():
try:
current = result.get()
result.set(eval(current))
except:
result.set("Error")
# 创建数字按键
for i in range(10):
button = tk.Button(window, text=str(i), width=5, height=2, command=lambda i=i: click(i))
button.grid(row=(i-1)//3+1, column=(i-1)%3)
# 创建运算符按键
button_add = tk.Button(window, text="+", width=5, height=2, command=lambda: click("+"))
button_add.grid(row=1, column=3)
button_sub = tk.Button(window, text="-", width=5, height=2, command=lambda: click("-"))
button_sub.grid(row=2, column=3)
button_mul = tk.Button(window, text="*", width=5, height=2, command=lambda: click("*"))
button_mul.grid(row=3, column=3)
button_div = tk.Button(window, text="/", width=5, height=2, command=lambda: click("/"))
button_div.grid(row=4, column=3)
button_equal = tk.Button(window, text="=", width=5, height=2, command=calculate)
button_equal.grid(row=4, column=2)
# 创建清空和退格按键
button_clear = tk.Button(window, text="C", width=5, height=2, command=clear)
button_clear.grid(row=4, column=1)
button_backspace = tk.Button(window, text="<-", width=5, height=2, command=backspace)
button_backspace.grid(row=1, column=2)
# 运行窗口
window.mainloop()
```
运行这段代码,会弹出一个窗口,其中包含一个显示窗口和数字、运算符、清空和退格等按键。用户可以通过按键输入算式,然后单击“=”按键进行计算,结果会显示在显示窗口中。
阅读全文