from tkinter import*
root = Tk()
root.geometry('500x300') #中间的乘号可用’x’字符
# 创建一个显示结果的标签
show = Label(root,font=('宋体', 24),width=23, bg='red')
show.pack()
# 创建Frame框架,摆放按钮
p = Frame(root)
p.pack()
b1 = Button(p, text='+', width=5)
b1.grid(row=0,column=0)
b2 = Button(p,text='1', width=5)
b2.grid(row=0,column=1)
b3 = Button(p,text='2', width=5)
b3.grid(row=0,column=2)
b4 = Button(p,text='3', width=5)
b4.grid(row=0,column=3)
b5 = Button(p,text='C', width=5)
b5.grid(row=0,column=4)
c1 = Button(p,text='-', width=5)
c1.grid(row=1,column=0)
c2 = Button(p,text='4', width=5)
c2.grid(row=1,column=1)
c3 = Button(p,text='5', width=5)
c3.grid(row=1,column=2)
c4 = Button(p,text='3', width=5)
c4.grid(row=1,column=3)
c5 = Button(p,text='=', width=5)
c5.grid(row=1,column=4)
def click1(event):
show['text']=show['text']+b1['text']
def click2(event):
show['text']=show['text']+b2['text']
def click3(event):
show['text']=show['text']+ b3['text']
def click5(event):
show['text'] = ''
def click10(event):
show['text'] = eval(show['text'])
b1.bind('<Button-1>', click1)
b2.bind('<Button-1>', click2)
b3.bind('<Button-1>', click3)
c5.bind('<Button-1>', click10)
names = ("+", "1", "2", "3", "C", "-", "4", "5", "6", "**", "*", "7", "8", "9", "//", "/", ".", "0", "%", "=")
# 遍历字符串元组
for i in range(len(names)):
#创建Button,将Button放入frame组件p中
b = Button(p,text=names[i],width=5)
b.grid(row=i// 5, column=i % 5)
# 为鼠标左键的单击事件绑定事件处理方法
b.bind('<Button-1>','click')
# 为鼠标左键的双击事件绑定事件处理方法
if b['text'] == 'C':
b.bind('<Button-1>','clean')
b1 = Button(p,text='+', width=5)
b1.grid(row=0,column=0)
b2 = Button(p,text='1', width=5)
b2.grid(row=0,column=1)
b3 = Button(p,text='2', width=5)
b3.grid(row=0,column=2)
b4 = Button(p,text='3', width=5)
b4.grid(row=0,column=3)
b5 = Button(p,text='C', width=5)
b5.grid(row=0,column=4)
c1 = Button(p,text='-', width=5)
c1.grid(row=1,column=0)
c2 = Button(p,text='4', width=5)
c2.grid(row=1,column=1)
c3 = Button(p,text='5', width=5)
c3.grid(row=1,column=2)
c4 = Button(p,text='3', width=5)
c4.grid(row=1,column=3)
c5 = Button(p,text='=', width=5)
c5.grid(row=1,column=4)
def click(event):
# 如果用户单击的是数字键或点号
if (event.widget['text'] in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.')):
show['text'] = show['text'] + event.widget['text']
# 如果用户单击了运算符
elif(event.widget['text'] in ('+', '-', '*', '/', '%', '**', '//')):
if show['text'][-1] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.']:
show['text'] = show['text'] + event.widget['text']
else:
show['text']=show['text']+''
elif(event.widget['text'] == '=' and show['text'] is not None):
show['text'] = eval(show['text'])
elif(event.widget['text'] =='C'):
show['text'] =''
root.mainloop()
为啥按钮按了显示不出来