用python设计一个窗体,窗体内各对象能进行四则运算
时间: 2024-03-10 15:47:13 浏览: 80
一个窗体的代码
好的,我可以帮你设计一个简单的窗体,用于进行四则运算。你需要安装 Python 的 GUI 库 tkinter。
以下是代码:
``` python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("四则运算计算器")
self.entry = tk.Entry(master, width=25, font=("Arial", 16))
self.entry.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
self.create_button("1", 1, 0)
self.create_button("2", 1, 1)
self.create_button("3", 1, 2)
self.create_button("+", 1, 3)
self.create_button("4", 2, 0)
self.create_button("5", 2, 1)
self.create_button("6", 2, 2)
self.create_button("-", 2, 3)
self.create_button("7", 3, 0)
self.create_button("8", 3, 1)
self.create_button("9", 3, 2)
self.create_button("*", 3, 3)
self.create_button("0", 4, 0)
self.create_button(".", 4, 1)
self.create_button("C", 4, 2)
self.create_button("/", 4, 3)
self.create_button("=", 5, 0, 1, 4)
def create_button(self, text, row, column, rowspan=1, columnspan=1):
button = tk.Button(self.master, text=text, width=5, height=2, font=("Arial", 16),
command=lambda: self.button_click(text))
button.grid(row=row, column=column, rowspan=rowspan, columnspan=columnspan, padx=5, pady=5)
def button_click(self, text):
if text == "C":
self.entry.delete(0, tk.END)
elif text == "=":
try:
result = eval(self.entry.get())
self.entry.delete(0, tk.END)
self.entry.insert(0, result)
except:
self.entry.delete(0, tk.END)
self.entry.insert(0, "Error")
else:
self.entry.insert(tk.END, text)
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
运行代码,就可以看到一个简单的四则运算计算器窗体。你可以点击窗体内的按钮进行相应的运算。
阅读全文