1

我创建了一个可以编辑文本文件内容的程序。假设我的程序看起来像这样:

from tkinter import *
from tkinter import filedialog

root = Tk()


def open_file():
    file_to_open = filedialog.askopenfilename(initialdir="C:/" , filetypes=(("All files" , "*.*"),))
    if file_to_open != "":
        file = open(file_to_open , 'r')
        content_in_file = file.read()
        file.close()
        text.delete('1.0' , END)
        text.insert('1.0' , content_in_file)


def save_file():
    path = filedialog.asksaveasfilename(initialdir="C:/" , filetypes=(("All files" , ""),))
    if path != "":
        file = open(path , 'w')
        file.write(text.get('1.0' , 'end-1c'))
        file.close()


text = Text(root , width = 65 , height = 20 , font = "consolas 14")
text.pack()

open_button = Button(root , text = "Open" , command = open_file)
open_button.pack()

save_button = Button(root , text = "Save" , command = save_file)
save_button.pack(pady=20)

mainloop()

这里的问题是,当我在文件资源管理器中单击文本文件时,它会使用默认的 Windows 记事本打开,而不是使用我的程序打开。

我想要的是所有文本文件都应该用我的程序打开,而不是用默认的 Windows 记事本打开。

这是我所做的(按顺序):

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

完成以下步骤后,我尝试打开我的文本文件,但它显示:

在此处输入图像描述

我尝试将我的 python 程序转换为一个exe文件(使用pyinstaller),然后按照上面的步骤操作,但是当我打开文本文件时,我得到了另一个错误:

在此处输入图像描述

我的代码或我遵循的步骤有什么问题吗?

如果有人能指导我如何使用我的程序打开文本文件,我将不胜感激。

4

1 回答 1

1

代码看起来不错,它只需要带参数,当您open-with在一个路径或多个路径上调用某个可执行文件时,第一个参数本身就是可执行文件,因此如果使用多个参数执行代码,它就是一个路径;问题在于命令是python而不是file.py,修复将其转换为exe或用bat调用它。

这个例子可能看起来不同,但或多或​​少是相同的,只是封装在一个类中。

from tkinter import filedialog
import tkinter as tk
import sys
import os

SRC_PATH = os.path.dirname(__file__)

class File_Editor(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.text = tk.Text(self, width=65, height=20, font="consolas 14")
        self.text.pack()
        self.open_button = tk.Button(self, text="Open", command=self.open_file)
        self.open_button.pack()
        self.save_button = tk.Button(self, text="Save", command=self.save_file)
        self.save_button.pack(pady=20)

    def open_file(self, file=None):
        path = file or filedialog.askopenfilename(
            initialdir=SRC_PATH, filetypes=(("All files", "*.*"),))
        if os.path.exists(path) and os.path.isfile(path):
            with open(path, 'r', encoding='utf-8') as file:
                content_in_file = file.read()
            self.text.delete('1.0', tk.END)
            self.text.insert('1.0', content_in_file)

    def save_file(self):
        path = filedialog.asksaveasfilename(initialdir=SRC_PATH, filetypes=(("All files", ""),))
        if os.path.exists(path) and os.path.isfile(path):
            with open(path, 'r', encoding='utf-8') as file:
                file.write(self.text.get('1.0', 'end-1c'))


if __name__ == '__main__':
    app = File_Editor()
    if len(sys.argv) > 1:
        app.open_file(sys.argv[1])
    app.mainloop()

这个 .bat 文件只是将第一个参数传递给文件;执行需要完整路径,它不会在您期望的目录中调用。

@echo off
python D:\Escritorio\tmp_py\temp_3.py %1

现在你只需调用open-with File_Editor.bat

于 2021-03-25T10:42:19.030 回答