我可以使用 F5 从 Notepad++ 打开任何 python 文件,除非它引用具有相对路径的图像。必须有一种方法可以让 Notepad++ F5 的工作方式与在 Windows 资源管理器中双击文件名或右键单击相同文件名“使用 IDLE 编辑”一样。如何让 Notepad++ 打开文件,而无需将计算机上存在的完整路径硬编码到我的 .py 文件中?我的应用程序的最终用户不需要我计算机上的路径。我找不到关于像我这样的初学者如何修复 NPP 来正确执行此操作的说明。我在 Windows 7 上使用 NPP v7.4.2 32 位。我尝试过 NPP 论坛,但其搜索引擎和 Google 都没有找到答案。
仅当我硬编码完整路径(如顶部未注释的代码行所示)时,F5 才能正确打开文件。
我以为我找到了答案这里但是当我尝试时看到下面的第二条错误消息
img4 = tk.PhotoImage(file=os.path.abspath("joe.gif") , master=root)
显然 NPP 强迫我使用绝对路径。
感谢您的帮助。
import tkinter as tk
root = tk.Tk()
# img4 = tk.PhotoImage(file="joe.gif", master=root)
img4 = tk.PhotoImage(file="c:/tkinter_code/joe.gif" , master=root)
logoimage = tk.Label(root, image=img4)
logoimage.image = img4
logoimage.grid()
root.mainloop()
Traceback (most recent call last):
File "C:\tkinter_code\how_to_get_npp_to_display_images_with_relative_path_tkinter.py", line 9, in <module> img4 = tk.PhotoImage(file="joe.gif", master=root) File "C:\Users\LUTHER\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3393, in __init__Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Users\LUTHER\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__ init__.py", line 3349, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open "joe.gif": no such file or directory
Traceback (most recent call last):
File "C:\tkinter_code\how_to_get_npp_to_display_images_with_relative_path_tkinter.py", line 14, in <module> img4 = tk.PhotoImage(file=os.path.abspath("joe.gif") , master=root) File "C:\Users\LUTHER\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3393, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Users\LUTHER\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3349, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open "C:\Program Files\Notepad++\joe.gif": no such file or directory
这就是答案。用 Python 完成这一切,这样我就不必更改 NPP:
import os
os.chdir("C:/tkinter_code")
通过添加 Python 方向,现在可以从 NPP F5、图像等正确打开文件。
你也可以这样做:
import sys
import os
## get the execution path
path = os.path.abspath(os.path.dirname(sys.argv[0]))
它可以移动到任何地方并且仍然可以工作。
但是,我想让 AKX 的答案起作用。自 2018 年以来,Notepad++ 发生了如此大的变化,以至于这个命令现在被破坏了吗?
cmd /K cd "$(CURRENT_DIRECTORY)" && python "$(FULL_CURRENT_PATH)"