import tkinter as tk
import tkinter.ttk as ttk
class TaxCalc(object):
taxPoint = 5000
def __init__(self):
self.top = tk.Tk()
self.top.title("个人所得税计算器")
sw,sh = self.top.winfo_screenwidth(),self.top.winfo_screenheight()
ww,wh = 245,280
self.top.geometry("{}x{}+{}+{}".format(ww,wh,(sw-ww)//2,(sh-wh)//2))
self.top.resizable(0,0)
self.createWdiget()
self.top.wm_attributes('-topmost',1) #主窗口置顶
self.top.mainloop()
def createWdiget(self):
self.beforeTaxLable = tk.Label(self.top,text="税前工资:")
self.beforeTaxLable.grid(row=0,column=0)
self.beforeTaxEntry = tk.Entry(self.top)
self.beforeTaxEntry.grid(row=0,column=1,pady=10,padx=10)
self.insuranceLable= tk.Label(self.top,text="扣除的保险:")
self.insuranceLable.grid(row=1,column=0)
self.insuranceEntry = tk.Entry(self.top)
self.insuranceEntry.grid(row=1,column=1,pady=10)
#绑定事件,离开焦点或按回车就试着调用计算的函数
self.insuranceEntry.bind("",self.calcTax)
self.insuranceEntry.bind("",self.calcTax)
self.sep = ttk.Separator(self.top, orient=tk.HORIZONTAL)
self.sep.grid(row=2,column=0,columnspan=2,sticky="ew")
self.taxAmoutLable = tk.Label(self.top,text="应纳税额:")
self.taxAmoutLable.grid(row=3,column=0)
self.taxAmoutEntry = tk.Entry(self.top)
self.taxAmoutEntry.grid(row=3,column=1,pady=10)
self.taxLable = tk.Label(self.top,text="应缴个税:")
self.taxLable.grid(row=4,column=0)
self.taxEntry = tk.Entry(self.top)
self.taxEntry.grid(row=4,column=1,pady=10)
self.afterTaxLable = tk.Label(self.top,text="税后工资:")
self.afterTaxLable.grid(row=5,column=0)
self.afterTaxEntry = tk.Entry(self.top)
self.afterTaxEntry.grid(row=5,column=1,pady=10)
self.calcBtn = ttk.Button(self.top,text="计算")
self.calcBtn.grid(row=6,column=1,pady=10)
self.calcBtn.bind("",self.calcTax) #不能直接用Button的command参数绑定,commmand默认不传event参数
def calcTax(self,event): #做为事件的回调函数须要有event参数
try:
beforeTax = float(self.beforeTaxEntry.get())
insurance = float(self.insuranceEntry.get())
except ValueError as e: #空或非数字转成浮点时都会捕获,但不做响应
pass
else:
taxAmout = beforeTax - insurance - TaxCalc.taxPoint if (beforeTax - insurance) > TaxCalc.taxPoint else 0
if taxAmout < 3000:
tax = taxAmout*0.03
elif taxAmout < 12000:
tax = taxAmout*0.1-210
elif taxAmout < 25000:
tax = taxAmout*0.2-1410
elif taxAmout < 35000:
tax = taxAmout*0.25-2660
elif taxAmout < 55000:
tax = taxAmout*0.3-4410
elif taxAmout < 80000:
tax = taxAmout*0.35-7160
else:
tax = taxAmout*0.45-15160
afterTax = beforeTax - insurance -tax
taxAmout = "{0:.2f}".format(taxAmout)
tax = "{0:.2f}".format(tax)
afterTax = "{0:.2f}".format(afterTax)
self.taxAmoutEntry.delete(0,tk.END)
self.taxAmoutEntry.insert(0, taxAmout)
self.taxEntry.delete(0,tk.END)
self.taxEntry.insert(0,tax)
self.afterTaxEntry.delete(0,tk.END)
self.afterTaxEntry.insert(0, afterTax)
if __name__ == '__main__':
s = TaxCalc()