import tkinter as tk
top=tk.Tk()
# 控件
shows=tk.Label(top,width=25,text="",bg="yellow")
shows.grid(row=0,column=0,columnspan=4)
one=tk.Button(top,text="1",width=5)
one.grid(row=1,column=0)
two=tk.Button(top,text="2",width=5)
two.grid(row=1,column=1)
three=tk.Button(top,text="3",width=5)
three.grid(row=1,column=2)
four=tk.Button(top,text="4",width=5)
four.grid(row=2,column=0)
five=tk.Button(top,text="5",width=5)
five.grid(row=2,column=1)
six=tk.Button(top,text="6",width=5)
six.grid(row=2,column=2)
seven=tk.Button(top,text="7",width=5)
seven.grid(row=3,column=0)
eight=tk.Button(top,text="8",width=5)
eight.grid(row=3,column=1)
nine=tk.Button(top,text="9",width=5)
nine.grid(row=3,column=2)
zero=tk.Button(top,text="0",width=5)
zero.grid(row=4,column=0)
add=tk.Button(top,text="+",width=5)
add.grid(row=1,column=3)
sub=tk.Button(top,text="-",width=5)
sub.grid(row=2,column=3)
mul=tk.Button(top,text="*",width=5)
mul.grid(row=3,column=3)
div=tk.Button(top,text="/",width=5)
div.grid(row=4,column=3)
dot=tk.Button(top,text=".",width=5)
dot.grid(row=4,column=1)
equal=tk.Button(top,text="=",width=5)
equal.grid(row=4,column=2)
#显示数字
press_opt=False
def num_action(num):
global press_opt
if press_opt:
shows["text"]=num
press_opt=False
else:
shows["text"]=shows["text"]+num
def zero_click():num_action("0")
zero["command"]=zero_click
def one_click():num_action("1")
one["command"]=one_click
def two_click():num_action("2")
two["command"]=two_click
def three_click():num_action("3")
three["command"]=three_click
def four_click():num_action("4")
four["command"]=four_click
def five_click():num_action("5")
five["command"]=five_click
def six_click():num_action("6")
six["command"]=six_click
def seven_click():num_action("7")
seven["command"]=seven_click
def eight_click():num_action("8")
eight["command"]=eight_click
def nine_click():num_action("9")
nine["command"]=nine_click
has_dot=False
def dot_click():
global has_dot
if not has_dot:
shows["text"]=shows["text"]+"."
has_dot=True dot["command"]=dot_click
# 计算
pre_opt=""
pre_num=0
def compute():
global pre_opt
global pre_num
if pre_opt=="":
return pre_opt
pre_num=eval(pre_num)
cur_num=eval(shows["text"])
if pre_opt=="+":
new_num=pre_num+cur_num
elif pre_opt=="-":
new_num=pre_num-cur_num
elif pre_opt=="*":
new_num=pre_num*cur_num
elif pre_opt=="/":
new_num=pre_num/cur_num
def opt_click(cur_opt):
global pre_opt
global pre_num
global press_opt
global has_dot
compute()
# 大概是这里少东西
#显示
pre_opt=False
def opt_click(opt):
global pre_opt
if pre_opt:
shows["text"]=opt
pre_opt=False
else:
shows["text"]=shows["text"]+opt
def add_click():opt_click("+")
add["command"]=add_click
def sub_click():opt_click("-")
sub["command"]=sub_click
def mul_click():opt_click("*")
mul["command"]=mul_click
def div_click():opt_click("/")
div["command"]=div_click
def dot_click():opt_click(".")
dot["command"]=dot_click
def equal_click():opt_click("=")
equal['command']=equal_click
top.mainloop()