import struct from tkinter import * from tkinter import messagebox #Frame:是tkinter框架控件,屏幕上会有个矩形区域,存放新增的东西 class Calculator(Frame): def __init__(self,master=None): # Frame.__init__(self,master,bg='red') Frame.__init__(self) self.pack(expand=YES, fill=BOTH) #要记得pack()的时候设置为全扩充 # self.master.geometry("320x210+500+200") self.master.title('计算器') self.master.rowconfigure( 0, weight = 2 ) self.master.columnconfigure( 0, weight = 2 ) self.grid( sticky = W+E+N+S ) text = Text(self, width=10, height=4) text.grid(row=0, column=0, columnspan=6, sticky= W+E+N+S) text.insert(INSERT, "\n") grid = '789+456-123*0./=' for index, textChar in enumerate(grid): a = Button(self, text=textChar, width=8) if a["text"] != "+" and a["text"] != "-" and a["text"] != "*" and a["text"] != "/" and a["text"] != "=": a["command"] = lambda tt=textChar:text.insert(INSERT, tt) elif a["text"] != "=": a["command"] = lambda tt=textChar:[ #此处拐了个弯 #如果不加tt+"\n",如果输入12+34+,第一行的结果会是12+3412++ #加上tt+"\n",输入12+34+,输出的结果是12+34+换行符12++ #之后text.delete(2.0, END)删除了上面换行符后面的内容就只剩12+34+,之后在第二行插入过回车换行符 #text.insert(1.0, text.get(1.0, END).replace('\n', '')), //可以这样测试看看输出什么 text.insert(1.0, text.get(1.0, END).replace('\n', '') + tt + "\n"), text.delete(2.0, END), text.insert(2.0, "\n"), #要达到计算器的效果,需要在这里插入表达式运算 ] else: a["command"] = lambda tt=textChar:[ text.insert(1.0, text.get(1.0, END).replace('\n', '') + tt + "\n"), text.delete(2.0, END), text.insert(2.0, "\n"), text.insert(2.0, eval(text.get(1.0, END).replace('\n', '')[:-1])) #表达式1+2+3=? 此处的-1是把=号去掉后进行运算,测试的时候有等号不能进行运算,会报错 ] a.grid(row=2 + index // 4, column=index % 4) # if a["text"] == '=': # a["command"]=lambda :text.insert("insert", "=\n"+str(eval(text.get(0.0, END)))) b = Button(self, text="clear", width=8) b["command"] = lambda :text.delete(0.0, END) b.grid(row=2, column=5, rowspan=4, sticky=W+E+N+S) if __name__ == '__main__': Calculator().mainloop() # 1 mainloop()方法允许程序循环执行,并进入等待和处理事件。 2、mainloop()方法的作用是监控每个组件,当组件发生变化或触发事件时,会立即更新窗口。