所以我正在寫一個程序,轉換貨幣爲學校項目。我嘗試使用盡可能多的循環和引用來使程序儘可能短。但我不斷收到錯誤本地變量引用之前,但我已經分配了它的值
"UnboundLocalError: local variable 'v3' referenced before assignment".
這是代碼(注:我修剪它,所以它只是必要的部分)。
from tkinter import *
root = Tk()
btn1 = StringVar()
btn2 = StringVar()
VALUTE = [ #besedilo v gumbu, oznaka, tečaj
("Evro", "evrov", 1),
("Dolar", "dolarjev", 1.12005),
("Funt", "funtov", 0.739868547),
]
v = v2 = v3 = v4 = 1
def funkcija():
n = int(entry1.get())
X = btn1.get()
Y = btn2.get()
for text, mark, convert in VALUTE:
if v3 == X:
o = convert
E = mark
v3 = v3 + 1
if v4 == Y:
p = convert
F = mark
v4 = v4 + 1
m = pretvorba(o,p)
print("%s %s je %s %s." % (n, E, m, F))
def pretvorba(a,b):
Q = n/a*b
return Q
for text, mark, convert in VALUTE:
gumb = Radiobutton(root, text=text, value = v, variable = btn1).grid(row = v+1, column=1, sticky=W)
v=v+1
for text, mark, convert in VALUTE:
gumb = Radiobutton(root, text=text, value = v2, variable = btn2).grid(row = v2+6, column=1, sticky=W)
v2=v2+1
entry1 = Entry(root)
entry1.grid(row=1, column=1, sticky=W)
go = Button(root, text="Izračun", fg="white", bg="black", command=funkcija)
go.grid(row=10, columnspan=3)
root.mainloop()
你的函數'funkcija'創建自己的'v3'變量,你讀它設置前。你可以告訴python不要在'funkcija'的開頭添加'global v3'語句來創建一個本地的v3' – FabienAndre
[Python中的UnboundLocalError]的可能的重複(http://stackoverflow.com/questions/9264763/unboundlocalerror-in-python ) – FabienAndre