【发布时间】:2020-11-18 02:06:01
【问题描述】:
文件“main.py”,第 47 行,在计算中 如果 (i.get() == 1): NameError: name 'i' is not defined
这就是我不断收到的错误,我不太明白为什么。如果有帮助,我主要是编码初学者。帮助将不胜感激,这里是代码。它是一个货币转换器,但目前不完整,因为我不明白错误是如何解决的
#the name of this app is MyFirstGui
class MyFirstGUI:
def __init__(self, master):
self.master = master
#The title
self.label_a = Label(master, text="~~~ Currency Converter ~~~")
self.label_a.pack(padx = 10, pady = 10)
#Where you would enter the amount of money
self.label_b = Label(master, text="Enter Amount of Money (CDN)")
self.label_b.pack()
self.money_entry = Entry(master)
self.money_entry.pack()
i = IntVar()
#These will make bubble buttons appear that you can check
rad1 = Radiobutton(master,text='US Dollar', value=1, variable=i)
rad2 = Radiobutton(master,text='British Pound', value=2, variable=i)
rad3 = Radiobutton(master,text='Chinese Yuan', value=3, variable=i)
rad4 = Radiobutton(master,text='Euro', value=4, variable=i)
rad5 = Radiobutton(master,text='South Korean Won', value=5, variable=i)
rad6 = Radiobutton(master,text='Mexican Peso', value=6, variable=i)
rad1.pack(pady = 5, anchor = 'w')
rad2.pack(pady = 5, anchor = 'w')
rad3.pack(pady = 5, anchor = 'w')
rad4.pack(pady = 5, anchor = 'w')
rad5.pack(pady = 5, anchor = 'w')
rad6.pack(pady = 5, anchor = 'w')
self.label_results = Label(master, text="")
self.label_results.pack(padx = 10, pady = 10)
#Button to calculate
self.button_a = Button(master, text="Calculate!", command=self.calculate)
self.button_a.pack()
#Where the calculations take place
def calculate(self):
if (i.get() == 1):
canadian_dollars = float(self.money_entry.get())
us_dollar = (canadian_dollars * 0.75)
self.label_results.config(text=("$%.2f Canadian Dollars will be equal to $%.2f when converted to US Dollars." % (canadian_dollars, us_dollar)))
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()```
【问题讨论】:
-
i是__init__()内部的局部变量,因此无法在calculate()内部访问。将i更改为self.i(或i以外的更好的名称)。