尝试使用此代码使用默认程序打开文件:
import webbrowser
from tkinter import *
from tkinter import filedialog # import needed modules
tk = Tk()
tk.geometry('700x600') # initialize tkinter window
def x():
f = filedialog.askopenfilename() # create function for opening file
webbrowser.open(f)
btn = Button(text="open file", command=x) # make a button to call x
btn.pack()
mainloop() # update
当您运行此代码时,应该会发生以下情况:
tkinter 窗口打开,给你一个打开文件按钮
单击按钮时,系统会提示您选择文件
选择文件后,它将在默认程序中打开。这适用于任何类型的文件。
假设你想用它的特定程序打开一个文件,你可以像这样使用内置的subprocess模块:
from tkinter import *
from tkinter import filedialog # import needed modules
import subprocess
tk = Tk()
tk.geometry('700x600') # initialize tkinter window
def x(): # make open file function
f = filedialog.askopenfilename()
p = subprocess.Popen(["C:\Program Files\GIMP 2\bin\gimp-2.10.exe", f]) # path of program and opened file
returncode = p.wait() # wait for notepad to exit
btn = Button(text="open file", command=x) # make a button to execute the
function
btn.pack()
mainloop() # update
始终确保指定用于打开文件的程序的完整文件路径。此外,如果您用来打开文件的程序路径中有任何斜杠(这些),请确保像我一样在每个斜杠后添加一个斜杠。
这两种方法都适用于任何文件类型。编码愉快!