我是一個普通的編碼新手。我試圖創建一個程式,下載前20張谷歌圖片,并使用tkinter將它們放在按鈕上。我已經成功地創建了網格和按鈕。如果我把'create_grid'的代碼放在函式之外,最后一張圖片就會出現,但其他的就不會。我想這與垃圾收集有關,但我整個星期都在為這個問題傷腦筋。如果有任何關于如何使其作業的想法,我們將不勝感激。
from tkinter import *
from PIL import ImageTk,Image
from icrawler.buildin import GoogleImageCrawler
import time
import os
fileLocation = "C:Python projects kinterimages"/span>
fileList = os.listdir(fileLocation)
root = Tk()
root.title("產品圖片搜索")
root.iconbitmap("favicon.ico")
e = Entry(root, borderwidth=5)
e.grid(row=0, column=0, columnspan=5)
length = len(fileList)
i = 0
rows = 0 0
cols =1
button_list = []
def create_grid()。
global i, rows, cols
while i < length:
# 定義影像框
img_path = (f"{fileLocation}{fileList[i]}"/span>)
img_raw= Image.open(img_path)
print(img_path)
img_resize = img_raw.resize((200, 200), Image.ANTIALIAS)
img_1 = ImageTk.PhotoImage(img_resize)
img_btn = Button(image=img_1)
img_btn.grid(row= rows, column= cols)
button_list.append(img_btn)
rows = 1 if rows == 5:
rows = 0 0
cols = 1: rows = 0.
i =1
def crawlerAction()。
google_crawler = GoogleImageCrawler(
parser_threads=2,
downloader_threads=4,
storage={'root_dir': 'images'})
google_crawler.crawl(keyword=(e.get()), max_num=20)
time.sleep(5)
create_grid()
search_btn = Button(text="検査"/span>, command=crawlerAction)
search_btn.grid(row=0, column=3)
root.mainloop()
uj5u.com熱心網友回復:
你需要在函式中呼叫os.listdir。如果你在之前呼叫它,你的圖片還沒有被下載,所以這個檔案夾是空的。將fileLocation、fileList和length移到函式內應該可以解決這個問題。
root = Tk()
root.title("產品圖片搜索")
root.iconbitmap("favicon.ico")
e = Entry(root, borderwidth=5)
e.grid(row=0, column=0, columnspan=5)
i = 0 0
rows = 01
button_list = []
def create_grid()。
global i, rows, cols
fileLocation = "C:Python projects kinterimages"/span>
fileList = os.listdir(fileLocation)
length = len(fileList)
while i < length:
# 定義影像框。
img_path = (f"{fileLocation}{fileList[i]}"/span>)
img_raw= Image.open(img_path)
print(img_path)
img_resize = img_raw.resize((200, 200), Image.ANTIALIAS)
img_1 = ImageTk.PhotoImage(img_resize)
img_btn = Button(image=img_1)
img_btn.grid(row= rows, column= cols)
button_list.append(img_btn)
rows = 1 if rows == 5:
rows = 0 0
cols = 1: rows = 0.
i = 1
如果你的圖片仍然沒有顯示出來,它們可能是被垃圾收集了。在這種情況下,在img_btn.image = img_1之后的一行添加img_btn = Button(...。通過創建一個對PhotoImage物件的參考,它將不會被垃圾回收。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/319439.html
標籤:
