【问题标题】:How to open pdf or txt files by filedialog.askopenfile in tkinter?如何在 tkinter 中通过 filedialog.askopenfile 打开 pdf 或 txt 文件?
【发布时间】:2022-11-14 10:52:18
【问题描述】:

在 tkinter 中使用 filedialog.askopenfile 后如何打开 pdf 或 txt 文件?

在我选择该文件夹中的文件并按打开后,是否有可能由其特定程序('Adobe reader')打开#?

from tkinter import *
from tkinter import filedialog as fd


def open_file():
    return fd.askopenfile()


window = Tk()
b_open = Button(window, text='Open file', command=open_file)
b_open.grid(row=0, column=0)

window.geometry('250x80')
window.mainloop()

【问题讨论】:

    标签: tkinter


    【解决方案1】:

    尝试使用此代码使用默认程序打开文件:

    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
    

    始终确保指定用于打开文件的程序的完整文件路径。此外,如果您用来打开文件的程序路径中有任何斜杠(这些),请确保像我一样在每个斜杠后添加一个斜杠。 这两种方法都适用于任何文件类型。编码愉快!

    【讨论】:

      猜你喜欢
      • 2013-07-07
      • 2020-06-27
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多