我从我制作的 Tkinter GUI 调用此脚本,我的一个变量无法从我的函数之一调用,我不明白为什么会这样?
我收到一个 NameError
,当我按下一个按键来触发我的 Tag 函数之一时,'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()
最佳答案
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
关于Python 模块名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42906206/