写一个带有界面的计算器python代码
时间: 2023-03-12 15:37:50 浏览: 90
这个代码可以实现创建一个带有界面的计算器:# 导入tkinter模块
import tkinter as tk# 创建一个窗口
win = tk.Tk()# 设置标题
win.title("计算器")# 创建一个文本框,用来显示运算的结果
e = tk.Entry(win, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)# 定义函数,用于实现计算器的功能
def button_click(number):
# 将用户输入的数字添加到文本框中
current = e.get()
e.delete(0, tk.END)
e.insert(0, str(current) + str(number))# 定义计算器的按钮
button_1 = tk.Button(win, text="1", padx=40, pady=20, command=lambda: button_click(1))
button_2 = tk.Button(win, text="2", padx=40, pady=20, command=lambda: button_click(2))
button_3 = tk.Button(win, text="3", padx=40, pady=20, command=lambda: button_click(3))
button_4 = tk.Button(win, text="4", padx=40, pady=20, command=lambda: button_click(4))
button_5 = tk.Button(win, text="5", padx=40, pady=20, command=lambda: button_click(5))
button_6 = tk.Button(win, text="6", padx=40, pady=20, command=lambda: button_click(6))
button_7 = tk.Button(win, text="7", padx=40, pady=20, command=lambda: button_click(7))
button_8 = tk.Button(win, text="8", padx=40, pady=20, command=lambda: button_click(8))
button_9 = tk.Button(win, text="9", padx=40, pady=20, command=lambda: button_click(9))
button_0 = tk.Button(win, text="0", padx=40, pady=20, command=lambda: button_click(0))
button_add = tk.Button(win, text="+", padx=39, pady=20, command=lambda: button_click("+"))
button_equal = tk.Button(win, text="=", padx=91, pady=20, command=lambda: button_click("="))
button_clear = tk.Button(win, text="Clear", padx=79, pady=20, command=lambda: button_click("Clear"))# 将按钮放入窗口中
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)button_0.grid(row=4, column=0)
button_clear.grid(row=4, column=1, columnspan=2)
button_add.grid(row=5, column=0)
button_equal.grid(row=5, column=1, columnspan=2)# 主事件循环
win.mainloop()
阅读全文