python - 如何从小部件的函数返回值,并将其传递给 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()
当我选择一个视频文件时,它的路径被打印出来。但。当我单击播放按钮时,会显示错误消息(请选择视频文件)。
解决方案
您需要在这两个函数的开头添加这一行,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()
推荐阅读
- java - 为什么 -XX:ReservedCodeCacheSize 没有被应用?
- dns - 如何连接到地理位置接近的数据中心
- python - 使 Spotipy 程序易于使用
- c - 代码块 C 调试
- xml - 如何按关键字过滤掉 XSLT 报告结果?
- webpack-4 - 使用 turbolinks,响应式菜单在页面加载时显示移动设备,在后续 turbolinks 加载时显示桌面
- swift - 以编程方式将肤色修饰符添加到表情符号
- sql - 如何忽略 SQL Server JSON 值中的几个属性
- typescript - 打字稿条件属性未检测到错误的功能参数
- python - 如何在类初始化时启动一个函数来设置子类中的属性?