import tkinter as tk
main = tk.Tk()
main.geometry('400x500')
main.title('計算器')
wint = tk.StringVar()
wint.set('0')
i = []

h1 = tk.Label(main,text='計算器',font=(' ',24))
h1.grid()

win = tk.Label(main,textvariable=wint)
win.grid(row=1,columnspan=3)

b1 = tk.Button(main,text=1,width=5,command=lambda: ip(1))
b1.grid(row=2,column=0,padx=5,pady=5)

b2 = tk.Button(main,text=2,width=5,command=lambda: ip(2))
b2.grid(row=2,column=1,padx=5,pady=5)

b3 = tk.Button(main,text=3,width=5,command=lambda: ip(3))
b3.grid(row=2,column=2,padx=5,pady=5)

# 四則運算按鈕
b_plus = tk.Button(main, text='+', width=5, command=lambda: ip('+'))
b_plus.grid(row=2, column=3, padx=5, pady=5)

b4 = tk.Button(main,text=4,width=5,command=lambda: ip(4))
b4.grid(row=3,column=0,padx=5,pady=5)

b5 = tk.Button(main,text=5,width=5,command=lambda: ip(5))
b5.grid(row=3,column=1,padx=5,pady=5)

b6 = tk.Button(main,text=6,width=5,command=lambda: ip(6))
b6.grid(row=3,column=2,padx=5,pady=5)

b_minus = tk.Button(main, text='-', width=5, command=lambda: ip('-'))
b_minus.grid(row=3, column=3, padx=5, pady=5)

b7 = tk.Button(main,text=7,width=5,command=lambda: ip(7))
b7.grid(row=4,column=0,padx=5,pady=5)

b8 = tk.Button(main,text=8,width=5,command=lambda: ip(8))
b8.grid(row=4,column=1,padx=5,pady=5)

b9 = tk.Button(main,text=9,width=5,command=lambda: ip(9))
b9.grid(row=4,column=2,padx=5,pady=5)

b_mul = tk.Button(main, text='*', width=5, command=lambda: ip('*'))
b_mul.grid(row=4, column=3, padx=5, pady=5)

b0 = tk.Button(main,text=0,width=5,command=lambda: ip(0))
b0.grid(row=5,column=1,padx=5,pady=5)

# 清除按鈕
bc = tk.Button(main,text='C',width=5,command=lambda: clear())
bc.grid(row=5,column=0,padx=5,pady=5)

# 等號按鈕
beq = tk.Button(main,text='=',width=5,command=lambda: calculate())
beq.grid(row=5,column=2,padx=5,pady=5)

b_div = tk.Button(main, text='/', width=5, command=lambda: ip('/'))
b_div.grid(row=5, column=3, padx=5, pady=5)

# 運算函式
def ip(ipp):
    global i
    i.append(ipp)
    wint.set("".join(map(str, i)))

def clear():
    global i
    i = []
    wint.set('0')

def calculate():
    global i
    a = ("".join(map(str, i)))
    if a=='16-9':
        wint.set('16-9，不夠借一，等於16-9......')
    else:
        try:
            result = eval("".join(map(str, i)))
            wint.set(str(result))
            i = list(str(result))
        except:
            wint.set("錯誤")
            i = []

main.mainloop()