[英]Keep getting an attribute error on my pygame project and I don't understand why
[英]so i keep getting this name error in my Tkinter code for a school project and i dont quite understand why
文件“main.py”,第 47 行,在計算 if (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函數中使用相同的 i 變量,您可以通過使用 self.i 而不是僅使用 i 使 i 成為實例變量,或者您可以將 i 作為參數傳遞給您的計算函數。
您在MyFirstGUI
的初始化函數中聲明了i
但您沒有擴展其范圍以包含其他函數,因此無法從您稍后聲明的calculate()
函數中訪問i
。 沒有上下文很難知道推薦什么,但請嘗試:
i
類,請在腳本頂部的MyFirstGUI
類之外聲明i
和root = Tk()
。i
僅在第一個 gui 類的上下文中使用,請使用self.i
和self.i.get()
。i
成為全局變量,但通常強烈建議不要這樣做。 如果您不打算添加更多引用i
類,那么重命名為self.i
以便i
繼承MyFirstGUI
的范圍將是最合適的方法。
如果您希望在單個函數的范圍之外使用i
(例如,跨越__init__()
和calculate()
那么我也強烈建議您將i
重命名為更具體的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.