我创建了一个gui,它允许您在输入小部件上输入货币金额,并允许您从组合框中选择要转换为哪种货币。单击按钮转换后,它将显示转换后的金额。 重置按钮不会将输入值重置为0,转换按钮不会在标签lblCurrency上显示任何内容。
root=Tk()
root.title("Currency converter")
root.geometry('1100x300+0+0')
root.configure(bg="black")
rightframe= Frame(root,width=100,height=400,bd=8,relief="raise")
rightframe.pack(side=RIGHT)
leftframe=Frame(root,width=660,height=400,bd=8,relief="raise")
leftframe.pack(side=LEFT)
#variables
value0=StringVar()
convert=DoubleVar()
currency=DoubleVar()
def Exit_():
Exit_=messagebox.askyesno("Exit System","Do you want to quit?")
if Exit_ >0:
root.destroy()
return
def Reset():
value0.set("Select Currency")
convert.set("0.0")
currency.set("0.0")
def currency():
if value0.get()=="USD":
convert1=float(EntCurrency.get() * 1.132099)
convert1="USD",str('%.2f'%(convert1))
currency.set(convert2)
elif value0.get()=="Britain Pound":
convert1=float(EntCurrency.get()* 0.072338)
convert1="British Pound",str('%.2f'%(convert1))
currency.set(convert2)
else:
print("Select currency")
EntCurrency=Entry(leftframe,font=("arial",20,"bold"),bd=2,width=15,justify="center")
EntCurrency.grid(row=0,column=2)
#EURO label
lblZARCurrency=Label(leftframe,font=("arial",20,"bold"),text=base,padx=2,pady=2,bd=2,fg="black",width=10)
lblZARCurrency.grid(row=0,column=1,sticky=W)
#combobox
CUrcombobox=ttk.Combobox(leftframe,textvariable=value0,state="readonly",font=("arial",20,"bold"),width=15)
CUrcombobox["values"]=('Select Currency','USD','GBP','ZMW','ZAR','JPY','EGP','BTC')
CUrcombobox.current(0)
CUrcombobox.grid(row=4,column=1)
lblCurrency=Label(leftframe,font=("arial",20,"bold"),textvariable=currency,padx=2,pady=2,bd=2,justify="center",fg="black",width=10)
lblCurrency.grid(row=4,column=2,sticky=W)
#BUTTONS
btnReset=Button(rightframe,text="Reset",bd=2,pady=2,command=Reset,padx=2,font=("ariel",20,"bold"),fg="black",width=12)
btnReset.grid(row=1,column=1)
btnConvert=Button(rightframe,text="Convert",command=currency,bd=2,pady=2,padx=2,font=("ariel",20,"bold"),fg="black",width=12)
btnConvert.grid(row=2,column=1)
btnExit=Button(rightframe,text="Exit",bd=2,pady=2,padx=2,command=Exit_,font=("ariel",20,"bold"),fg="black",width=12)
btnExit.grid(row=3,column=1)
root.mainloop()
如果单击RESET按钮,则会出现此错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\user\Anaconda3\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "<ipython-input-103-81c819d1cb46>", line 49, in Reset
currency.set("0.0")
AttributeError: 'function' object has no attribute 'set'
如果在组合框中选择美元后单击“转换”按钮,则会出现此错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\user\Anaconda3\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "<ipython-input-103-81c819d1cb46>", line 53, in currency
convert1=float(EntCurrency.get() * USD)
TypeError: can't multiply sequence by non-int of type 'float'
如果在组合框中选择GBP后单击“转换”按钮,它将仅运行最后一个iF条件并打印“选择货币”