我不能在python tkin中调用def命令内部的变量

2024-04-19 01:23:31 发布

您现在位置: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

Tags: importappmovedefcreatewidthleftgrid
1条回答
网友
1楼 · 发布于 2024-04-19 01:23:31

Tkinter取消了这个变量,所以要阻止这种情况发生,您需要使用 在声明变量时使用此代码

n1 = IntVar()
n1.set(0)

然后调用变量use:

n1.get() 

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

variable = StringVar()

然后是和以前一样的代码

相关问题 更多 >