import tkinter as tk class Calculator: def init(self, master): self.master = master master.title("Calculator") self.label1 = tk.Label(master, text="Operand 1:") self.label1.grid(row=0, column=0) self.entry1 = tk.Entry(master) self.entry1.grid(row=0, column=1) self.label2 = tk.Label(master, text="Operand 2:") self.label2.grid(row=1, column=0) self.entry2 = tk.Entry(master) self.entry2.grid(row=1, column=1) self.label3 = tk.Label(master, text="Result:") self.label3.grid(row=2, column=0) self.entry3 = tk.Entry(master, state="readonly") self.entry3.grid(row=2, column=1) self.add_button = tk.Button(master, text="+", command=self.add) self.add_button.grid(row=3, column=0) self.subtract_button = tk.Button(master, text="-", command=self.subtract) self.subtract_button.grid(row=3, column=1) self.multiply_button = tk.Button(master, text="*", command=self.multiply) self.multiply_button.grid(row=4, column=0) self.divide_button = tk.Button(master, text="/", command=self.divide) self.divide_button.grid(row=4, column=1) def add(self): operand1 = self.entry1.get() operand2 = self.entry2.get() if operand1.isdigit() and operand2.isdigit(): result = int(operand1) + int(operand2) self.entry3.configure(state="normal") self.entry3.delete(0, tk.END) self.entry3.insert(0, str(result)) self.entry3.configure(state="readonly") def subtract(self): operand1 = self.entry1.get() operand2 = self.entry2.get() if operand1.isdigit() and operand2.isdigit(): result = int(operand1) - int(operand2) self.entry3.configure(state="normal") self.entry3.delete(0, tk.END) self.entry3.insert(0, str(result)) self.entry3.configure(state="readonly") def multiply(self): operand1 = self.entry1.get() operand2 = self.entry2.get() if operand1.isdigit() and operand2.isdigit(): result = int(operand1) * int(operand2) self.entry3.configure(state="normal") self.entry3.delete(0, tk.END) self.entry3.insert(0, str(result)) self.entry3.configure(state="readonly") def divide(self): operand1 = self.entry1.get() operand2 = self.entry2.get() if operand1.isdigit() and operand2.isdigit() and int(operand2) != 0: result = int(operand1) / int(operand2) self.entry3.configure(state="normal") self.entry3.delete(0, tk.END) self.entry3.insert(0, str(result)) self.entry3.configure(state="readonly") root = tk.Tk() calculator = Calculator(root) root.mainloop(),帮我解释以上代码
时间: 2024-02-19 09:01:57 浏览: 168
Python tkinter教程-02:Label标签
以上代码是一个简单的计算器GUI程序,使用tkinter库实现。程序中定义了一个Calculator类,其中包含了4个按钮和3个文本框,用于输入两个操作数和展示计算结果。
在Calculator类中,实现了四个方法,分别对应加、减、乘、除四种计算操作。这些方法通过获取文本框中的操作数进行计算,然后将结果展示在结果文本框中。
最后,在程序的主函数中创建了一个Tk()对象作为根窗口,并将其传给Calculator类的构造函数,以创建一个完整的计算器GUI程序。调用mainloop()方法启动程序的事件循环,等待用户的交互操作。
阅读全文