-2

I've been trying to take frames of a video and play them in TKinter when a button is pressed. However, the video starts playing as soon as I run the application. Can someone show me where I am going wrong?

def __init__(self, window, delay):

        self.window = window
        self.delay = 15
        window.title("User Interface")
        self.video_source = "movie.mov"
        self.vid = 0
        self.canvas = Canvas(window, width = 400, height = 400)
        self.canvas.pack()
        self.hiButton = Button(window, text="hello", command = self.callback)
        self.hiButton.pack()
        self.getFeedButton = Button(window, text = "Get Feed", \
                                    command = self.feedCallBack(window,"movie.mov"))
        self.getFeedButton.pack()

    def update(self):
        ret, frame = self.get_frame()

        if ret:
            self.photo = ImageTk.PhotoImage(image = Image.fromarray(frame))
            self.canvas.create_image(0, 0, image = self.photo, anchor = tkinter.NW)
        self.window.after(self.delay, self.update)
    def callback(self):
        self.guess = Test()
        print('hi')

    def feedCallBack(self, window, video_source):
        self.vid = cv2.VideoCapture(video_source)
        self.update()

        #self.window.after(self.delay, self.update)
    def get_frame(self):
        ret, frame = self.vid.read()
        if ret:
            return (ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
        else:
            return (ret, None)

I would think from this code that the video would only play when getFeed is clicked, but that is not what is happening.

2 Answers2

1
self.getFeedButton = Button(window, text = "Get Feed", \
                                    command = self.feedCallBack(window,"movie.mov"))

should be

self.getFeedButton = Button(window, text = "Get Feed", \
                                    command = lambda: self.feedCallBack(window,"movie.mov"))
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
  • Thank you! That works! Can you explain how the lambda expression causes this change? – CSCSCSCSCSCSCSCSCS Mar 20 '20 at 16:10
  • `function` is a object.In your code,`command = self.feedCallBack(window,"movie.mov")` means that when python run this,it will call the function,and finally,The real ``command`` of the ``button`` is the **returned value** of the `feedCallBack(window,"movie.mov")`. – jizhihaoSAMA Mar 20 '20 at 16:13
1

Use lambda function

 self.getFeedButton = Button(window, text = "Get Feed", 
                                command = lambda: self.feedCallBack(window,"movie.mov"))
 self.getFeedButton.pack()
Jordan
  • 525
  • 1
  • 4
  • 19