la=tk.Label(root,text=‘’,bg=‘white’,fg=‘black’,font=(‘宋体’,24),anchor=‘w’,relief=‘flat’) #生成输入框
la.grid(column=0,row=0,columnspan=5,rowspan=1,sticky=‘we’)
lab=tk.Label(root,bg=‘white’,fg=‘grey’,height=1,font=(‘宋体’,22),anchor=‘w’,relief=‘flat’) #生成显示框
lab.grid(column=0,row=1,columnspan=5,rowspan=1,sticky=‘we’)
上面创建两个标签,作为输入框和显示框。
la
是输入框,lab
是显示框(这名字定的有点随意哈不要介意,你们可以定一些喜欢的名字)。
然后定义函数 grid_rowconfigure
和 grid_columnconfigure
,用于自动填充行和列:
def grid_rowconfigure(*rows): #函数填充行。*rows:允许接收多个参数
for i in rows:
root.grid_rowconfigure(i,weight=1)
def grid_columnconfigure(*cols): #函数填充列。*cols:允许接收多个参数
for i in cols:
root.grid_columnconfigure(i,weight=1)
在窗体被改变大小时,按钮会自动填充四周,而输入、显示框只填充左右两边(第2,3,4,5,6行会向竖直方向填充,每一列都会向水平方向填充)。
grid_rowconfigure(2,3,4,5,6)
grid_columnconfigure(0,1,2,3,4)
定义 text_print
函数,当按钮被点击时输入内容,当按钮“=”被点击的时候计算结果:
def text_print(x): #函数按钮输入算式
global textchange,equal_is #声明全局变量
if x!=‘=’:
if x==‘←’:
a=str(textchange)[0:-1]
textchange=a #退格
elif x==‘C’:
textchange=‘’ #清空
else:
textchange=str(textchange)+str(x) #输入
la.configure(text=textchange)
show_is()
equal_is=False #判断格式有无错误
if x==‘=’:
text_equal() #计算结果
show_is
用于判断格式有无错误:
def show_is(): #显示框内容
global textchange #声明全局变量
if textchange!=‘’:
try:
te