编写程序:选择合适的布局管理器,制作基本的运算器的GUI界面
时间: 2024-02-27 14:53:23 浏览: 49
构建运算器
好的,以下是一个简单的运算器GUI界面的代码,使用了GridLayout布局管理器:
``` python
import tkinter as tk
class CalculatorGUI:
def __init__(self, master):
self.master = master
master.title("Calculator")
# 创建显示结果的文本框
self.result_display = tk.Entry(master, width=20, justify="right")
self.result_display.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
# 创建数字和操作符按钮
self.buttons = [
tk.Button(master, text="7", width=5, command=lambda: self.button_click("7")),
tk.Button(master, text="8", width=5, command=lambda: self.button_click("8")),
tk.Button(master, text="9", width=5, command=lambda: self.button_click("9")),
tk.Button(master, text="+", width=5, command=lambda: self.button_click("+")),
tk.Button(master, text="4", width=5, command=lambda: self.button_click("4")),
tk.Button(master, text="5", width=5, command=lambda: self.button_click("5")),
tk.Button(master, text="6", width=5, command=lambda: self.button_click("6")),
tk.Button(master, text="-", width=5, command=lambda: self.button_click("-")),
tk.Button(master, text="1", width=5, command=lambda: self.button_click("1")),
tk.Button(master, text="2", width=5, command=lambda: self.button_click("2")),
tk.Button(master, text="3", width=5, command=lambda: self.button_click("3")),
tk.Button(master, text="*", width=5, command=lambda: self.button_click("*")),
tk.Button(master, text="0", width=5, command=lambda: self.button_click("0")),
tk.Button(master, text=".", width=5, command=lambda: self.button_click(".")),
tk.Button(master, text="C", width=5, command=lambda: self.button_click("C")),
tk.Button(master, text="/", width=5, command=lambda: self.button_click("/")),
tk.Button(master, text="=", width=5, command=lambda: self.button_click("="))
]
# 将按钮添加到GUI中
for i, button in enumerate(self.buttons):
row = 1 + i // 4
col = i % 4
button.grid(row=row, column=col, padx=5, pady=5)
# 处理按钮点击事件
def button_click(self, text):
if text == "=":
try:
result = eval(self.result_display.get())
self.result_display.delete(0, tk.END)
self.result_display.insert(0, str(result))
except:
self.result_display.delete(0, tk.END)
self.result_display.insert(0, "Error")
elif text == "C":
self.result_display.delete(0, tk.END)
else:
self.result_display.insert(tk.END, text)
if __name__ == "__main__":
root = tk.Tk()
gui = CalculatorGUI(root)
root.mainloop()
```
这个GUI界面包含一个文本框和16个按钮,可以进行简单的四则运算。每个按钮都有一个对应的命令,当被点击时会调用button_click方法。在button_click方法中,如果按钮是数字或操作符,则将其添加到文本框中;如果是等号,则计算文本框中的表达式并将结果显示在文本框中;如果是C,则清空文本框;如果出现错误,则在文本框中显示"Error"。
阅读全文