首页 > 解决方案 > 如何从小部件的函数返回值,并将其传递给 Tkinter,Python 中的另一个小部件的函数

问题描述

我正在创建一个简单的 GUI,包括两个按钮。第一个按钮用于选择视频文件,第二个按钮获取视频文件路径然后播放(使用 OpenCV)。

问题是我无法从第一个按钮绑定函数返回文件路径并将其传递给第二个按钮绑定函数。

我将“文件名”定义为全局变量,但“PlayVideo()”函数中仍未定义“文件名”。

以下是我的代码:

from tkinter import *
from tkinter import filedialog
from tkinter import messagebox

global filename


def OpenFile():
    filename =  filedialog.askopenfilename(title = "Select file",filetypes = ( ("MP4 files","*.mp4"), ("WMV files","*.wmv"), ("AVI files","*.avi") ))
    print(filename)


def PlayVideo():
    try:
        import cv2

        cap = cv2.VideoCapture(filename)

        while(cap.isOpened()):

            ret, frame = cap.read()

            cv2.imshow('frame', frame)

            if cv2.waitKey(25) & 0xFF == ord('q'):
                break
        cap.release()
        cv2.destroyAllWindows()

    except:
        messagebox.showinfo(title='Video file not found', message='Please select a video file.')


root = Tk()

selectButton = Button(root, text = 'Select video file', command=OpenFile)
playButton = Button(root, text = 'Play', command=PlayVideo)

selectButton.grid(row=0)
playButton.grid(row=1)

root.mainloop()   

当我选择一个视频文件时,它的路径被打印出来。但。当我单击播放按钮时,会显示错误消息(请选择视频文件)。

标签: pythontkintercommandreturn-valuevideo-capture

解决方案


您需要在这两个函数的开头添加这一行,OpenFile并且PlayVideo

global filename

当您添加这一行时,您的程序知道,它必须使用全局变量“filename”,而不是在该函数中创建/使用局部变量“filename”。

更新:

为避免使用全局变量,您可以像这样使用可变类型。

from tkinter import *
from tkinter import filedialog
from tkinter import messagebox

def OpenFile(file_record):
    file_record['video1'] =  filedialog.askopenfilename(title = "Select file",filetypes = ( ("MP4 files","*.mp4"), ("WMV files","*.wmv"), ("AVI files","*.avi") ))
    print(file_record['video1'])

def PlayVideo(file_record):

    try:
        import cv2
        cap = cv2.VideoCapture(file_record['video1'])

        while(cap.isOpened()):
            ret, frame = cap.read()
            cv2.imshow('frame', frame)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                break

        cap.release()
        cv2.destroyAllWindows()

    except:
        messagebox.showinfo(title='Video file not found', message='Please select a video file.')


root = Tk()
filename_record = {}
selectButton = Button(root, text = 'Select video file', command=lambda: OpenFile(filename_record))
playButton = Button(root, text = 'Play', command=lambda: PlayVideo(filename_record))

selectButton.grid(row=0)
playButton.grid(row=2)

root.mainloop()

推荐阅读