用Tkinter做一个简易计算器:
from tkinter import *
master = Tk()
master.title('pandarking\'s calculator')
frame1 = Frame(master)
frame1.pack(padx=10, pady=10)
frame2 = Frame(master)
frame2.pack(padx=10, pady=10)
proceed = StringVar()
num = StringVar()
result = StringVar()
operate = StringVar()
result.set(' ')
num.set(' ')
proceed.set('0')
operate.set(' ')
def get_num(i):
temp = num.get()
temp = temp + i
num.set(temp)
def calc(symbol):
if symbol == '+':
temp1 = int(num.get())
operate.set('+')
num.set(' ')
proceed.set(temp1)
if symbol == '-':
temp1 = int(num.get())
operate.set('-')
num.set(' ')
proceed.set(temp1)
if symbol == '*':
temp1 = int(num.get())
operate.set('*')
num.set(' ')
proceed.set(temp1)
if symbol == '/':
temp1 = int(num.get())
operate.set('/')
num.set(' ')
proceed.set(temp1)
if symbol == '=':
temp1 = int(num.get())
temp2 = int(proceed.get())
if operate.get() == '+':
temp3 = temp1 + temp2
if operate.get() == '-':
temp3 = temp2 - temp1
if operate.get() == '*':
temp3 = temp1 * temp2
if operate.get() == '/':
temp3 = temp2 / temp1
num.set(' ')
proceed.set(temp3)
result.set(temp3)
show_num = Label(frame1, bg='white', fg='black', width=30, textvariable=num, anchor='e').grid(row=0)
show_result = Label(frame1, bg='white', fg='black', width=30, textvariable=result, anchor='e').grid(row=1)
Button(frame2, bg='darkgray', width=10, text='1', command=lambda: get_num('1')).grid(row=2, column=0)
Button(frame2, bg='darkgray', width=10, text='2', command=lambda: get_num('2')).grid(row=2, column=1)
Button(frame2, bg='darkgray', width=10, text='3', command=lambda: get_num('3')).grid(row=2, column=2)
Button(frame2, bg='darkgray', width=10, text='4', command=lambda: get_num('4')).grid(row=3, column=0)
Button(frame2, bg='darkgray', width=10, text='5', command=lambda: get_num('5')).grid(row=3, column=1)
Button(frame2, bg='darkgray', width=10, text='6', command=lambda: get_num('6')).grid(row=3, column=2)
Button(frame2, bg='darkgray', width=10, text='7', command=lambda: get_num('7')).grid(row=4, column=0)
Button(frame2, bg='darkgray', width=10, text='8', command=lambda: get_num('8')).grid(row=4, column=1)
Button(frame2, bg='darkgray', width=10, text='9', command=lambda: get_num('9')).grid(row=4, column=2)
Button(frame2, bg='gray', width=10, text='+', command=lambda: calc('+')).grid(row=5, column=0)
Button(frame2, bg='gray', width=10, text='-', command=lambda: calc('-')).grid(row=5, column=1)
Button(frame2, bg='gray', width=10, text='*', command=lambda: calc('*')).grid(row=5, column=2)
Button(frame2, bg='gray', width=10, text='/', command=lambda: calc('/')).grid(row=6, column=0)
Button(frame2, bg='gray', width=10, text='=', command=lambda: calc('=')).grid(row=6, column=1)
mainloop()
截图: