Closing video window using close "X" button in OpenCV, Python

With the cv2 Python module there is a way to do that, I posted the solution here:

https://stackoverflow.com/a/37881722/2897426

This post is just for reference so anyone looking for it can find it


I had this same issue and I found an easy way to do it:

You can use cv2.getWindowProperty(windowName, cv2.WND_PROP_VISIBLE) to check if the current window is visible, and if it's not you can destroy the window. The method returns a 1 if it is visible and 0 if it is not. Below is an implementation:


while True: 
    _, frame = cap.read()

    cv2.imshow(windowName, frame)
    keyCode = cv2.waitKey(1)

    if cv2.getWindowProperty(windowName, cv2.WND_PROP_VISIBLE) <1:
        break
cv2.destroyAllWindows()

The accepted answer links to a solution that will never work as 0 is included in >=0, and uses the wrong second argument in cv2.getWindowProperty(), while the issues only gets indirectly solved later in the thread. I'm adding this as an answer as I could not find the correct solution when I first visited this thread, and this was exactly what I needed and used.