這個問題在這里已經有了答案: tkinter PhotoImage 不存在? (2 個回答) 昨天關閉。
我正在嘗試創建一個功能,看看一個專案是否在購物車串列中,并從我存盤影像的檔案夾中放置一個影像,但是當我運行代碼時,它說 filenotfound 錯誤,當我在舊執行緒中查找它時人們說我必須寫出實際路徑
imagenames=[]
path1="C:\\Users\\3a2b\\Desktop\\lib\\images"
imagelist=os.listdir(path1)
for name in os.listdir(path1):
imagenames.append(os.path.splitext(name)[0])
def show_cart():
cartwindow = Toplevel()
for item in cart:
for i in range(len(imagenames)):
if item.title == imagenames[i]:
print("its there")
img = ImageTk.PhotoImage(open(os.listdir(path1)[i]))
label = Label(cartwindow,image=img)
label.grid(row=0,column=2)
```
uj5u.com熱心網友回復:
如果您在其中運行腳本,則C:\\Users\\3a2b\\Desktop可以將images目錄作為相對路徑參考,例如.\\lib\\images.
如果您在另一個目錄中C:\\Users\\3a2b\\Documents\\Scripts\\script.py,則可以像這樣參考您的影像路徑..\\..\\Desktop\\lib\\images。
如果你想在 Python 中瀏覽你的目錄,你可以嘗試以下方法:
currentPath = 'C:\\Users\\3a2b\\Desktop'
currentPath = os.chdir('..\\..')
print(os.getcwd())
-> 'C:\\Users'
查看os包裝以獲取更多資訊。https://docs.python.org/3/library/os.html
另外,請注意您安裝 Python 發行版的位置,我在 C: 驅動器上安裝了一次,并且無法訪問另一個驅動器 D: 或 E: 中的資料,而沒有一些額外的麻煩。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/385742.html
