用python tkinter写一个计算器
时间: 2023-11-20 19:07:27 浏览: 168
好的,我可以为您提供一个基本的计算器程序。以下是代码:
``` python
import tkinter as tk
# 创建主窗口
root = tk.Tk()
root.title("简易计算器")
# 创建显示框
display = tk.Entry(root, width=30, font=("Arial", 16), justify="right")
display.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# 定义按钮点击事件
def button_click(num):
current = display.get()
display.delete(0, tk.END)
display.insert(0, str(current) + str(num))
def button_clear():
display.delete(0, tk.END)
def button_equal():
try:
result = eval(display.get())
display.delete(0, tk.END)
display.insert(0, result)
except:
display.delete(0, tk.END)
display.insert(0, "Error")
# 创建按钮
button_1 = tk.Button(root, text="1", padx=20, pady=10, command=lambda: button_click(1))
button_2 = tk.Button(root, text="2", padx=20, pady=10, command=lambda: button_click(2))
button_3 = tk.Button(root, text="3", padx=20, pady=10, command=lambda: button_click(3))
button_4 = tk.Button(root, text="4", padx=20, pady=10, command=lambda: button_click(4))
button_5 = tk.Button(root, text="5", padx=20, pady=10, command=lambda: button_click(5))
button_6 = tk.Button(root, text="6", padx=20, pady=10, command=lambda: button_click(6))
button_7 = tk.Button(root, text="7", padx=20, pady=10, command=lambda: button_click(7))
button_8 = tk.Button(root, text="8", padx=20, pady=10, command=lambda: button_click(8))
button_9 = tk.Button(root, text="9", padx=20, pady=10, command=lambda: button_click(9))
button_0 = tk.Button(root, text="0", padx=20, pady=10, command=lambda: button_click(0))
button_add = tk.Button(root, text="+", padx=20, pady=10, command=lambda: button_click("+"))
button_sub = tk.Button(root, text="-", padx=20, pady=10, command=lambda: button_click("-"))
button_mul = tk.Button(root, text="*", padx=20, pady=10, command=lambda: button_click("*"))
button_div = tk.Button(root, text="/", padx=20, pady=10, command=lambda: button_click("/"))
button_clear = tk.Button(root, text="清除", padx=20, pady=10, command=button_clear)
button_equal = tk.Button(root, text="=", padx=20, pady=10, command=button_equal)
# 按钮放置在布局中
button_1.grid(row=1, column=0)
button_2.grid(row=1, column=1)
button_3.grid(row=1, column=2)
button_add.grid(row=1, column=3)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_sub.grid(row=2, column=3)
button_7.grid(row=3, column=0)
button_8.grid(row=3, column=1)
button_9.grid(row=3, column=2)
button_mul.grid(row=3, column=3)
button_0.grid(row=4, column=0)
button_clear.grid(row=4, column=1)
button_equal.grid(row=4, column=2)
button_div.grid(row=4, column=3)
# 运行主窗口
root.mainloop()
```
这个程序使用 `tkinter` 模块创建了一个简单的 GUI 计算器。它包括数字键、运算符键和清除键以及等于键。当用户点击这些按键时,程序会将相应的数字或符号添加到显示框中。当用户点击等号键时,程序会计算并显示结果。
阅读全文