在python中导入图像,如果我把程序文件夹移到不同的地方,我的程序就无法工作.如果我想让它运行,我必须更改我的代码



我的程序有问题,我导入了图像,它很有效,但在成功的背后,我缺少了一些东西。查看以下代码片段:

# python 3
from PIL import Image
from PIL import ImageTk
pathdesign_img = "D:/Python/Project1/image/design/
self.logo_Tbar_img = ImageTk.PhotoImage(Image.open(pathdesign_img+'Mlogo.jpg'))
self.logo_Tbar = tk.Label(self.bar_Tbar, image=self.logo_Tbar_img, bg="#DA291C")
self.logo_Tbar.pack(side=tk.LEFT, fill=tk.BOTH)

代码有效,但当我想将所有程序文件夹移动到不同的位置时,例如:C:User。我的程序无法运行,如果我想让它运行,我必须更改pathdesign_img = "C:/User/...."。是否有任何代码需要更改或添加,以便我的程序可以在任何文件夹中运行,而无需更改pathdesign_img

是的,相对于应用程序目录的路径是正确的解决方案,但在将它们转发使用时,建议始终使用绝对路径。因此,您使用相对于应用程序目录的绝对路径。

它可以很容易:

import os
dirpath   = os.path.abspath("images")
# os.path.abspath() will return the absolute path of the directory images
# that resides in the current working directory which you can discover with
# os.getcwd() and manipulate using os.chdir()
# Note that the current working directory may be manipulated from the OS.
# In the Windows's case you can specify it under properties of the shortcut
# and/or the executable. By the default it is the same directory where
# the executable lives, in this case, your script.
imagepath = os.path.join(dirpath, "<some_image>.jpg")

应该这样做。它是跨平台的,良好的实践,不会给你带来路径上的麻烦。

然而,如果你打算将你的应用程序捆绑到例如EXE中,你需要比这更狡猾。这是因为*.exe捆绑应用程序实际上是一个添加了一些内容的ZIP文件。在这种情况下,图像路径将看起来像:

>>> print (imagepath)
C:Program FilesYours_app_folderyourapp.exeimagesyour_image.jpg

这当然是OS的无效路径。在这些情况下,我会执行以下操作。我创建了一个名为wheriam或wheerami的模块(这个名字取决于我的感觉(,我在其中放入一个var或函数,为我的应用程序目录提供正确的路径。例如

import os, sys
def root ():
# If the app is only a script, this will result in mydir
# being a path to the directory where the 'whereiam' module lives:
me = os.path.abspath(__file__)
mydir = os.path.dirname(me)
# If the app is bundled then sys.executable points to it instead
# of Python interpreter, so first check for that
if mydir.startswith(sys.executable):
# Then we first get the directory where our app lives:
mydir = os.path.dirname(sys.executable)
# And if our whereiam is in a subdirectory, we find it by excluding
# the executable's filename from the path:
# by appending the rest to the mydir
l = len(sys.executable)
mydir = os.path.join(mydir.rstrip(os.sep), me[l:].lstrip(os.sep))
return mydir

然后在你的主模块中,你只需要做:

import whereiam
import os
dirpath   = whereiam.root()
images    = os.path.join(dirpath, "images")
imagepath = os.path.join(images, "<your_image>.jpg")
# And you can then open imagepath with PIL or whatever being sure that it will be found if it is there

是的,这应该是可能的。我假设你的python文件或jupyter笔记本在文件夹"中;D:/Python/Project1";,而你的图像在文件夹"中;D: Python/Project1/images/design";。然后你可以做:

pathdesign_img = "image/design/"

简而言之,它的作用是:在你已经所在的文件夹中,它搜索一个名为"的文件夹;图像";并且在该文件夹中用于名为"的子文件夹;设计";。

相关内容

最新更新