用Python写一段带UI界面的计算器程序
时间: 2023-02-21 19:21:22 浏览: 104
你可以使用Python GUI库, 比如 tkinter, PyQt, wxPython等来实现一个带有用户界面的计算器程序.
具体来说, 你需要创建一个界面, 在界面上放置按钮和文本框, 然后编写相应的代码实现计算器的功能.
以下是一个使用tkinter库创建计算器界面的简单代码示例:
```
import tkinter as tk
root = tk.Tk()
root.title("Calculator")
e = tk.Entry(root, 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))
def button_clear():
e.delete(0, tk.END)
def button_add():
first_number = e.get()
global f_num
f_num = int(first_number)
e.delete(0, tk.END)
def button_equal():
second_number = e.get()
e.delete(0, tk.END)
e.insert(0, f_num + int(second_number))
# Define buttons
button_1 = tk.Button(root, text="1", padx=40, pady=20, command=lambda: button_click(1))
button_2 = tk.Button(root, text="2", padx=40, pady=20, command=lambda: button_click(2))
button_3 = tk.Button(root, text="3", padx=40, pady=20, command=lambda: button_click(3))
button_4 = tk.Button(root, text="4", padx=40, pady=20, command=lambda: button_click(4))
button_5 = tk.Button(root, text="5", padx=40, pady=20, command=lambda: button_click(5))
button_6 = tk.Button(root, text="6", padx=40, pady=20, command=lambda: button_click(6))
button_7 = tk.Button(root, text="7", padx=40, pady=20, command=lambda: button_click(7))
button_8 = tk.Button(root, text="8", padx=40, pady=20, command=lambda: button_click(8))
阅读全文