首页 > 解决方案 > 在继续执行之前让函数等待 tkinter root.after() 循环完成

问题描述

我调用了一个函数playVideo(),然后使用 tkinter 循环获取视频帧root.after(5, playVideo)。在我调用 playVideo 之后,我有更多的代码来处理填充在 playVideo 中的列表。问题是这段代码在 playVideo 循环完成之前执行。

有没有办法强制程序等待 playVideo() 完成后再继续?

def myFunc():
    global myList

    # call to the looping function
    playVideo()

    # some code that handles the list

def playVideo():
    global myList

    ret, frame = currCapture.read()

    if not ret:
        currCapture.release()
        print("Video End")
    else:
        # some code that populates the list

        root.after(5, playVideo)

标签: pythonasynchronoustkinter

解决方案


您可以尝试使用wait_variable()功能:

# create a tkinter variable
playing = BooleanVar()

然后使用wait_variable()等待完成playVideo()

def myFunc():
    global myList
    # call to the looping function
    playVideo()
    # some code that handles the list
    print('Handling list ...')
    # wait for completion of playVideo()
    root.wait_variable(playing)
    # then proceed
    print('Proceed ...')

def playVideo()
    global myList
    ret, frame = currCapture.read()
    if not ret:
        currCapture.release()
        print("Video End")
        playing.set(False) # update variable to make wait_variable() return
    else:
        # some code that populates the list
        root.after(5, playVideo)

推荐阅读