提供一段python的计算器设计gui代码
时间: 2023-04-04 21:00:48 浏览: 137
以下是一个简单的 Python 计算器 GUI 代码示例:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("计算器")
self.display = tk.Entry(master, width=30, justify="right")
self.display.grid(row=, column=, columnspan=4, padx=5, pady=5)
# 按钮
self.create_button("7", 1, )
self.create_button("8", 1, 1)
self.create_button("9", 1, 2)
self.create_button("/", 1, 3)
self.create_button("4", 2, )
self.create_button("5", 2, 1)
self.create_button("6", 2, 2)
self.create_button("*", 2, 3)
self.create_button("1", 3, )
self.create_button("2", 3, 1)
self.create_button("3", 3, 2)
self.create_button("-", 3, 3)
self.create_button("", 4, )
self.create_button(".", 4, 1)
self.create_button("C", 4, 2)
self.create_button("+", 4, 3)
self.create_button("=", 5, , columnspan=4)
def create_button(self, text, row, column, columnspan=1):
button = tk.Button(self.master, text=text, width=5, height=2, command=lambda: self.button_click(text))
button.grid(row=row, column=column, columnspan=columnspan, padx=5, pady=5)
def button_click(self, text):
if text == "C":
self.display.delete(, tk.END)
elif text == "=":
try:
result = eval(self.display.get())
self.display.delete(, tk.END)
self.display.insert(, result)
except:
self.display.delete(, tk.END)
self.display.insert(, "Error")
else:
self.display.insert(tk.END, text)
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
这是一个基本的计算器 GUI,包括数字、运算符、小数点、清除和等于按钮。用户可以通过单击按钮来输入数字和运算符,并在显示器中查看结果。
阅读全文