我是从我制作的Tkinter调用这个脚本的,我的一个变量不能从我的函数中调用,我不知道为什么会发生这种情况?
当我按下键触发一个标记函数时,我得到了一个没有定义NameError的'framevalues'。
提前感谢!
import cv2
import tkinter as tk
from tkinter.filedialog import askopenfilename
def main():
framevalues = []
count = 1
selectedvideo = askopenfilename()
selectedvideostring = str(selectedvideo)
cap = cv2.VideoCapture(selectedvideo)
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
while (cap.isOpened()):
ret, frame = cap.read()
# check if read frame was successful
if ret == False:
break
# show frame first
cv2.imshow('frame',frame)
# then waitKey
frameclick = cv2.waitKey(0) & 0xFF
if frameclick == ord('a'):
swingTag(cap)
elif frameclick == ord('r'):
rewindFrames(cap)
elif frameclick == ord('s'):
stanceTag(cap)
elif frameclick == ord('d'):
unsureTag(cap)
elif frameclick == ord('q'):
with open((selectedvideostring + '.txt'), 'w') as textfile:
for item in framevalues:
textfile.write("{}\n".format(item))
break
else:
continue
cap.release()
cv2.destroyAllWindows()
def stanceTag(cap):
framevalues.append('0' + ' ' + '|' + ' ' + str(int(cap.get(1))))
print (str(int(cap.get(1))), '/', length)
print(framevalues)
def swingTag(cap):
framevalues.append('1' + ' ' + '|' + ' ' + str(int(cap.get(1))))
print (str(int(cap.get(1))), '/', length)
print(framevalues)
def unsureTag(cap):
framevalues.append('-1' + ' ' + '|' + ' ' + str(int(cap.get(1))))
print (str(int(cap.get(1))), '/', length)
print(framevalues)
def rewindFrames(cap):
cap.set(1,((int(cap.get(1)) - 2)))
print (int(cap.get(1)), '/', length)
framevalues.pop()
print(framevalues)
if __name__ == '__main__':
# this is called if this code was not imported ... ie it was directly run
# if this is called, that means there is no GUI already running, so we need to create a root
root = tk.Tk()
root.withdraw()
main()发布于 2017-03-20 14:33:50
framevalues是在main()中定义的局部变量,因此在其他函数中不可见。您可以使它是全局的,即在main()之前定义它,也可以将它从main()传递给其他函数作为正常函数参数。
def main():
...
if frameclick == ord('a'):
swingTag(cap, framevalues) # pass it as a parameter
...
...
def swingTag(cap, framevalues):
framevalues.append(...) # now you are using local framevalues passed as parameter发布于 2017-03-20 14:34:58
framevalues是一个本地到main()的变量。您需要将framevalues作为参数传递给所有需要它的函数,以便它们能够访问它。
请仔细阅读变量范围。我建议在Short Description of the Scoping Rules?中给出答案
发布于 2017-03-20 14:40:32
分配变量时,您将在当前作用域(即当前函数的本地)中创建该变量。
因此,您可以做的是将framevalues变量定义为全局。可以做到以下几点:
替换
framevalues = [] 使用
global framevalues
framevalues = []您不需要更改代码的其余部分,这将很好地工作。
https://stackoverflow.com/questions/42906206
复制相似问题