为什么捕获视频不会在 tkinter 循环中刷新? [英] why capture video does not refresh in tkinter loop?
问题描述
我期待视频捕获刷新屏幕.当它不是一堂课时,它按我的预期工作.然后我将它转换为 oop -below.它没有刷新......然后我预计之后"会完成这项工作.显然我不明白之后如何工作?它不是连续调用 - 在我的情况下 - root.vidImg.vid() .如果是,为什么 self.cap = cv2.VideoCapture(0) 不捕获并显示新图像?提前感谢您的帮助
I am expecting video capture refreshes the screen. When it was not a class it was working as I expected. Then I converted it to oop -below. It did not refresh... Then I expected "after" would do the work. Apperently I did not understand how after works? Does not it call -in my case below- root.vidImg.vid() continuously. If yes why self.cap = cv2.VideoCapture(0) does not captures and shows a new image? Thanks for the helps in advance
这是我的代码...
import tkinter as tk
from PIL import Image, ImageTk
import cv2
class Window(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.videoFrm = tk.Frame(self, width=480, bg='yellow', height=320)
self.videoFrm.grid(row=0, column=0, sticky=tk.NW)
self.vidImg = cnvs(self.videoFrm,self)
self.vidImg.grid()
class cnvs(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
self.controller = controller
self.canvas = tk.Canvas(self, width=480, height=320, bg='green')
self.canvas.grid()
def vid(self):
# Capture video frames
self.cap = cv2.VideoCapture(0)
_, self.frame = self.cap.read()
self.img = cv2.flip(self.frame, 1)
self.cv2image = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGBA)
self.cv2image = cv2.resize(self.cv2image, (0, 0), fx=0.2, fy=0.2)
self.img = Image.fromarray(self.cv2image)
self.imgtk = ImageTk.PhotoImage(image=self.img)
self.canvas.create_image(10, 10, anchor=tk.NW, image=self.imgtk)
def main():
root = Window()
root.after(0, root.vidImg.vid())
root.mainloop()
if __name__ == '__main__':
main()
推荐答案
使用 after
创建一个动画循环code>方法,需要让动画函数多次调用自身.
To create an animation loop with the after
method, you need to let the animation function call itself multiple times.
在您的情况下,您可以将以下方法添加到 cnvs
类:
In your case, you could add the following method to the cnvs
class:
def video_loop(self):
self.vid()
self.controller.after(10, self.video_loop)
然后在 mainloop()
之前调用它.
and then call it just before the mainloop()
.
此外,与其为每一帧向画布添加新图像,不如仅更改现有图像 使用 canvas.itemconfig(...)
.
Furthermore, instead of adding a new image to the canvas for each frame, it's probably better to just change the existing image using canvas.itemconfig(...)
.
这篇关于为什么捕获视频不会在 tkinter 循环中刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!