如何在Tkinter中获取文件并在其他命令中调用?
解决Tkinter中play函数无法访问select_file内filename的问题
问题根源是select_file里的filename是局部变量,作用域仅限该函数内部,play函数自然拿不到它。下面给你三种可行的解决办法:
方法1:使用全局变量
在函数外部定义全局的filename,然后在select_file里声明要使用这个全局变量,这样就能把选中的文件路径存进去供play调用:
import tkinter as tk from tkinter import filedialog as fd import vlc import time root = tk.Tk() filename = "" # 全局变量 def select_file(): global filename # 声明使用全局变量 filetypes = (('mp3 files', '*.mp3'),) filename = fd.askopenfilename( title='Select audio', initialdir='/', filetypes=filetypes) def play(): if filename: # 先判断是否选中了文件 p = vlc.MediaPlayer(filename) p.play() time.sleep(60) # 选择文件按钮(原代码遗漏,需补充) select_btn = tk.Button(root, text="Select MP3", command=select_file) select_btn.place(x=20, y=40) play_button = tk.Button(root, text='Play', command=play) play_button.place(x=20, y=10) root.mainloop()
方法2:用类封装(更推荐,避免全局变量混乱)
把整个界面逻辑封装到类里,filename作为实例属性,两个方法都能直接访问,这是更规范的写法:
import tkinter as tk from tkinter import filedialog as fd import vlc import time class MP3Player: def __init__(self, root): self.root = root self.filename = "" # 实例属性 # 创建按钮 self.play_btn = tk.Button(root, text='Play', command=self.play) self.play_btn.place(x=20, y=10) self.select_btn = tk.Button(root, text="Select MP3", command=self.select_file) self.select_btn.place(x=20, y=40) def select_file(self): filetypes = (('mp3 files', '*.mp3'),) self.filename = fd.askopenfilename( title='Select audio', initialdir='/', filetypes=filetypes) def play(self): if self.filename: p = vlc.MediaPlayer(self.filename) p.play() time.sleep(60) if __name__ == "__main__": root = tk.Tk() app = MP3Player(root) root.mainloop()
方法3:把路径存到按钮属性里
不用全局变量也不用类,直接把选中的路径绑定到play_button的自定义属性上:
import tkinter as tk from tkinter import filedialog as fd import vlc import time root = tk.Tk() def select_file(): filetypes = (('mp3 files', '*.mp3'),) filename = fd.askopenfilename( title='Select audio', initialdir='/', filetypes=filetypes) play_button.filename = filename # 把路径存到按钮属性里 def play(): if hasattr(play_button, 'filename') and play_button.filename: p = vlc.MediaPlayer(play_button.filename) p.play() time.sleep(60) play_button = tk.Button(root, text='Play', command=play) play_button.place(x=20, y=10) select_btn = tk.Button(root, text="Select MP3", command=select_file) select_btn.place(x=20, y=40) root.mainloop()
注意:不管用哪种方法,最好加个判断,确保用户确实选中了文件再执行播放逻辑,避免空路径报错。
内容的提问来源于stack exchange,提问作者Riz
相关产品推荐
相关产品推荐

