0

在此主题失败后:使用 python 和 opencv 显示完整图像时出现白色边框。我决定改变我的方法,为了显示全屏黑色图像,我使用了 PIL 和 Tkinter 库。但我一直在寻找一种方法来关闭我的全黑图像,但我无法弄清楚。我的解决方案应该类似于下面的代码,使用来自 openCv 的键。

import Tkinter as tk
from PIL import ImageTk
from PIL import Image
import cv2
import numpy as np


root = tk.Tk()
root.title('background image')
imageFile = "nera.jpg"
image1 = ImageTk.PhotoImage(Image.open(imageFile))
w = image1.width()
h = image1.height()
x = 0
y = 0
root.geometry("%dx%d+%d+%d" % (w, h, x, y))
panel1 = tk.Label(root, image=image1)
panel1.pack(side='top', fill='both', expand='yes')
panel1.image = image1
root.overrideredirect(True)

root.mainloop()

key=cv2.waitKey(0)&0xFF
while True:
    if key==ord('d') or key==ord('a')  or key==ord('s') or key==ord('w') or key==27:
        root.destroy()
        print 'ciao

我怎样才能关闭它并做其他事情然后再次打开它?谢谢

4

1 回答 1

1

两个问题。首先,您永远不会读取密钥并且永远不会到达 while 循环,因为它 root.mainloop(). 其次,如果程序进入循环,它永远不会离开它,因为没有break. 因此,要修复您的方法,请尝试以下方法:

# comment out root.mainloop() or just remove the line

while True:
    key=cv2.waitKey(0)&0xFF
    if key==ord('d') or key==ord('a')  or key==ord('s') or key==ord('w') or key==27:
        root.destroy()
        print 'ciao'
        break

或者,您可以只使用 tkinter 方法使小部件响应按键,而不是诉诸丑陋的 openCV hack:

root.bind("a", lambda x: root.destroy())
root.bind("d", lambda x: root.destroy())
root.bind("s", lambda x: root.destroy())
root.bind("w", lambda x: root.destroy())
root.bind("<Escape>", lambda x: root.destroy())

root.mainloop()
于 2013-08-06T20:40:31.830 回答