【问题标题】:Open a file from pc into tkinter从 pc 打开文件到 tkinter
【发布时间】:2021-12-02 14:43:13
【问题描述】:

可以在 tkinter 中使用 pc 右键单击​​->打开方式->我的程序打开文件。 我只想要使用这种方法时的文件路径。

【问题讨论】:

  • 当然,您可以使用 RegEdit 创建“打开方式”选项。不过,该答案并非特定于 Python 或 tkinter.... “获取文件路径”是什么意思?
  • 简化我想要的。我有一个带有列表框的 GUI。假设我想用我的程序打开一个 txt 文件。我要做的就是获取 txt 文件路径并将其插入到我的列表框中。我不想要txt文件的内容,只想要路径。我知道filedialog,但我想右键单击txt文件->打开方式->我的程序
  • 假设是windows,你需要把你的应用转成exe,或者使用python.exe script.py %1。请参阅此处的示例idojo.co/…

标签: python getopenfilename


【解决方案1】:

您无法使用您要求的方法打开文件(右键单击 > 打开方式 > 我的程序),但您可以使用 Tkinter file dialog 库和open()函数。

我所说的方法的一个例子:

from tkinter import *
from tkinter.filedialog import askopenfilename

windows = Tk()
windows.title("File Dialog Example")
windows.geometry("500x500")


def file_open():
    text_window.delete('1.0', END)
    filePath = askopenfilename(
        initialdir='C:/', title='Select a File', filetype=(("Text File", ".txt"), ("All Files", "*.*")))
    with open(filePath, 'r+') as askedFile:
        fileContents = askedFile.read()

    text_window.insert(INSERT, fileContents)
    print(filePath)


open_button = Button(windows, text="Open File", command=file_open).grid(row=4, column=3)
text_window = Text(windows, bg="white",width=200, height=150)
text_window.place(x=50, y=50)

windows.mainloop()

为了保存对文件的更改,您可以读取文本框中的内容,然后将内容写入打开的文件。

谢谢

【讨论】:

  • 感谢您的回复。我知道文件对话框。
猜你喜欢
  • 1970-01-01
  • 2011-07-24
  • 2013-05-02
  • 1970-01-01
  • 2020-03-30
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
相关资源
最近更新 更多