I was just looking for a way to detect when the window has been closed using the X button of the window in addition to waiting for a key press, but I couldn’t find an answer anywhere (IsWindowVisible and cvGetWindowHandle are not available in the Python cv2 module).
So I played around and this is how it works:
while cv2.getWindowProperty('window-name', 0) >= 0:
keyCode = cv2.waitKey(50)
# ...
cv2.getWindowProperty() returns -1 as soon as the window is closed.
For explanation, see the documentation for the enumeration of cv::WindowPropertyFlags: getting the flag with index 0 is the fullscreen property, but actually it doesn’t matter which flag to use, they all become -1 as soon as the window is closed.
Note: This might only work for certain GUI backends. Notably, it will not work with the GTK backend used in Debian/Ubuntu packages. To use the Qt backend instead, you have to install opencv-python via pip.