以下是我的代码中包含if elif语句的部分内容。由于某种原因,代码在调用时输出if语句,但在调用时忽略elif。请帮忙:
if cv2.waitKey(1) == 32: # 32 is also equal to spacebar.
break
elif cv2.waitKey(1) == 27: # 27 is equal to escape
name = input("Name the file:")
testimage = ("'%s'.jpg".format(img_counter) %name)
cv2.imwrite(testimage, frame)
print("Picture saved!")
img_counter += 1
choice = input("Do you want to post to facebook?(Y/n)")
if choice == 'Y':
print("Posting now!")
elif choice == 'n':
print("Ok not posting.")
答案 0 :(得分:1)
按下该键后,您有机会获取其值。如上所述,您试图在 if 块的上下文中“实时读取”按键。问题是,一旦评估了条件,按键结束并退出 if 块。它永远不会到达 elif 部分。考虑捕获变量中的值(正如Jim Lewis在评论中建议的那样),然后测试该变量的值。
关于您的代码示例,当32为真时没有任何事情发生。这只是一个不完整的代码段来说明您的问题吗?如果这样无视。否则,您可以按如下方式编写它:
keyPressed = cv2.waitKey(1)
if keyPressed == 27:
name = input("Name the file:")
testimage = ("'%s'.jpg".format(img_counter) %name)
cv2.imwrite(testimage, frame)
print("Picture saved!")
img_counter += 1
choice = input("Do you want to post to facebook? (Y/n)")
if choice == 'Y':
print("Posting now!")
else:
print("Ok not posting.")