我无法在python tkinter中的def命令中调用变量

时间:2015-03-28 09:23:29

标签: python

由于某种原因,我无法在def命令中调用变量。听到的是代码:

from tkinter import *
import time
app = Tk()
app.title('movement')
canvas=Canvas(app,bg='Black',width=300,height=300)
canvas.create_oval(0,0,30,30,fill='Green')
canvas.grid(row=0,column=0)
n1 = 0
n2 = 0
n3 = 30
n4 = 30
n=100
def move_left():
    n1 = n1+n
    n3 = n3+n
    canvas=Canvas(app,bg='Black',width=300,height=300)
    canvas.create_oval(0+n1,0+n2,0+n3,0+n4,fill='Green')
    canvas.grid(row=0,column=0)
    n = n+n
button_left = Button(app,text='->',command=move_left)
button_left.grid()
app.mainloop()

出现的错误是:

line 14, in move_left
n1 = n1+n
UnboundLocalError: local variable 'n1' referenced before assignment

1 个答案:

答案 0 :(得分:0)

变量被Tkinter废弃,以便停止您需要使用的事件 声明变量时的代码

n1 = IntVar()
n1.set(0)

然后调用变量use:

n1.get() 

请注意,如果您想在变量中使用字符串并出现相同的错误,请使用

variable = StringVar()

然后使用与之前相同的代码