Python Tkinter货币计算器Float乘以RadioButton var

时间:2016-05-02 09:16:49

标签: python variables tkinter floating-point radio-button

我正在制作货币转换器并收到试图返回值(从单选按钮)乘以用户输入的问题。从下拉菜单中触发toNZD和fromNZD,这将很快更改。感谢任何人的意见。

from tkinter import *
mGui = Tk()

number=0
currency=StringVar()
tester=0

def fromNZD():
    global tester
    currencySelect=currency.get()
    if currencySelect ==1:
        tester = 0.4 #eg's
    elif currencySelect ==2:
        tester= 1.2 #eg's

    userInput=number.get()
    final=(float(userInput)*(tester))#<-------
    mlabel2=Label(mGui,text='${0:.2f}!'.format(final)).pack()


def toNZD():
    userInput2=number.get()
    userInput2=(float(userInput2)/0.6)
    mlabel3=Label(mGui,text='${0:.2f}!'.format(userInput2)).pack()

def terminate():
    global mGui
    mGui.destroy()


menu = Menu(mGui)
mGui.config(menu=menu)

tofrom = StringVar(mGui)
tofrom.set("To") #initial value

subMenu = Menu(menu)
menu.add_cascade(label="Currency Settings", menu=subMenu)
subMenu.add_command(label="From NZD", command=fromNZD)
subMenu.add_separator()
subMenu.add_command(label="To NZD", command=toNZD)

editMenu = Menu(menu)
menu.add_cascade(label="Options", menu=editMenu)
editMenu.add_command(label="Exit", command=terminate)

mlabel = Label(text='Currency Calculator',bg="orange red", fg='gray20',font=("Century Gothic",20))
mlabel.pack(fill=X)

Radiobutton(mGui, text="GBP", variable=currency, value=1, indicatoron=0).pack()
Radiobutton(mGui, text="USD", variable=currency, value=2, indicatoron=0).pack()


number=Entry(mGui,textvariable=number)
number.pack(pady=8)

mGui.configure(background='deepskyblue3')
mGui.geometry('450x450+500+300')
mGui.title('Currency Converter')
mGui.mainloop()

1 个答案:

答案 0 :(得分:0)

currencyStringVar(),因此currency.get()会返回string。您正试图在currencySelect方法中将fromNZD()与整数(1或2)进行比较。因此,两个比较都失败了,tester变量没有变化(仍为0),自tester = 0起,乘法结果为0。

您可以将currency.get()转换为整数

currencySelect= int(currency.get())

或将currencySelect与字符串值("1""2"等)进行比较。

currencySelect=currency.get()
    if currencySelect == "1":
        tester = 0.4 #eg's
    elif currencySelect == "2":
        tester= 1.2 #eg's

此外,最好包含一个else语句,以防万一出错。可能会打印错误或弹出消息。