简洁计算器Python代码

发布时间:2024年01月10日

简洁的Python计算器,直接上代码(用时10分钟):

Python Gui图形化开发探索GUI开发的无限可能,使用强大的PyQt5、默认的Tkinter和跨平台的Kivy等工具,让Python成为你构建应用程序的得力助手。从本机用户界面到现代触摸设备的开源Libavg,再到PySimpleGUI的简化入门,每个工具都有其独特的优势。PyForms让你在不同平台上创建高度交互的应用程序,而Wax作为wxPython的友好包装器提供更简单的访问方式。PySide2作为Qt的官方模块提供验证过的工具和库,而轻量级的PyGUI框架则简化了Python应用程序的本机用户界面创建。无论你是新手还是经验丰富的开发者,这些工具都能满足你对于GUI开发的各种需求。icon-default.png?t=N7T8https://fostmar.online/archives/471/

import tkinter as tk

def button_click(number):
    current = entry.get()
    entry.delete(0, tk.END)
    entry.insert(0, current + str(number))

def clear():
    entry.delete(0, tk.END)

def calculate():
    try:
        result = eval(entry.get())
        entry.delete(0, tk.END)
        entry.insert(0, str(result))
    except Exception as e:
        entry.delete(0, tk.END)
        entry.insert(0, "Error")

def key_press(event):
    if event.keysym in ("Return", "="):
        calculate()
    elif event.keysym == "c":
        clear()
    elif event.keysym in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"):
        button_click(event.keysym)
    elif event.keysym in ("plus", "minus", "asterisk", "slash"):
        button_click("+" if event.keysym == "plus" else "-" if event.keysym == "minus" else "*" if event.keysym == "asterisk" else "/")

root = tk.Tk()
root.title("Calculator")
root.geometry("340x400")

entry = tk.Entry(root, width=16, font=("Arial", 24), bd=10, relief=tk.SUNKEN, justify=tk.RIGHT)
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10, ipady=10)

buttons = [
    "7", "8", "9", "/",
    "4", "5", "6", "*",
    "1", "2", "3", "-",
    "0", ".", "=", "+"
]

row_val = 1
col_val = 0

for button_text in buttons:
    tk.Button(root, text=button_text, width=4, height=2, font=("Arial", 20), command=lambda text=button_text: button_click(text) if text != "=" else calculate()).grid(row=row_val, column=col_val, padx=5, pady=5)
    col_val += 1
    if col_val > 3:
        col_val = 0
        row_val += 1

tk.Button(root, text="C", width=4, height=2, font=("Arial", 20), command=clear).grid(row=row_val, column=col_val, padx=5, pady=5)

# 绑定键盘事件
root.bind("<KeyPress>", key_press)

root.mainloop()
文章来源:https://blog.csdn.net/2301_81307082/article/details/135512359
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。