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 Files\Yours_app_folder\yourapp.exe\images\your_image.jpg

もちろん、これはOSにとって無効なパスです。これらの場合、私は次のことを行います。whereiamまたはwhereami(名前は私が推測する方法によって異なります)というモジュールを作成します。このモジュールには、アプリのディレクトリへの正しいパスを取得する変数または関数を配置します。例えば

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

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ