我可以同时更改多张图片吗?

1 投票
1 回答
55 浏览
提问于 2025-04-14 17:25

在我上一个问题中提到,我正在制作一个传送带,它可以从一个文件夹中提取图片,并让这些图片从左到右移动。最近出现了一个意想不到的问题,我已经在用canvas.image = (新图片)来更换图片,以便让传送带动画运行。我原以为可以用同样的方法来处理其他物体:

#Import
import os
import random 
from PIL import Image, ImageTk
from tkinter import Tk, Canvas, PhotoImage, NW
from tkinter import Label

# folder path
dir_path = r'C:\Users\Usuario\Downloads\Experiment'

#------------------------------------------------------------Select Random Image--------------------------------------------------------

imgExtension = ["webp","png"] #Image Extensions to be chosen from
allImages = list()

def Makelist(directory):
    for img in os.listdir(directory): #Lists all files
        ext = img.split(".")[len(img.split(".")) - 1]
        if (ext in imgExtension):
            allImages.append(img)
    return allImages

Makelist(dir_path)
global potatoes
potatoes = allImages
choice = random.randint(0, len(potatoes) - 1)
randomImage = potatoes[choice] #Image chosen
print(randomImage)
potatoes.remove(randomImage)

#------------------------------------------------------------Canvas---------------------------------------------------------------
root = Tk()
root.attributes('-transparentcolor','#f0f0f0')

canvas = Canvas(root, width = root.winfo_screenwidth(), height=300)
canvas.pack()
#-------------------------------------------------------Conveyor belt gif------------------------------------------------------------
file = r'C:\Users\Usuario\Downloads\Python\Cinta'
allImages = []
Makelist(file)
conveyor = allImages
global current_con
current_con = 0
print(conveyor)
conveyori = Image.open(file+"/"+conveyor[current_con])
conveyorimg = ImageTk.PhotoImage(conveyori)
conveyor_canva = canvas.create_image(0, 0, anchor=NW, image = conveyorimg)
conveyor_label = Label(canvas, image = conveyorimg)
conveyor_label = conveyorimg
def animation():
    global current_con
    if (current_con < 3):
        current_con += 1
    else:
        current_con = 0
    conveyori = Image.open(r'C:/Users/Usuario/Downloads/Python/Cinta/'+conveyor[current_con])
    conveyorimg = ImageTk.PhotoImage(conveyori)
    canvas.itemconfig(conveyor_canva, image = conveyorimg)
    canvas.image  = conveyorimg
    canvas.after(105, animation)
#-------------------------------------------------------------Potato a image setup------------------------------------------------------------------
im_O = Image.open(r'C:/Users/Usuario/Downloads/Experiment/'+ randomImage)
new_image = im_O.resize((100, 100))
potimg = ImageTk.PhotoImage(new_image)
potato_label = Label(canvas, image = potimg)
potato_label = potimg
#-----------------------------------------------------Positioning the Image inside the canvas-------------------------------------------------------
imga = canvas.create_image(root.winfo_screenwidth()+20, 100, anchor=NW, image = potimg)
#---------------------------------------------------------------Potato a movement setup--------------------------------------------------------------
global pos
pos = root.winfo_screenwidth()+20
def move_imga():
    global pos
    global potatoes
    pos -= 5
    # move the image
    canvas.move(imga, -5, 0)
    if (pos < -90):
        #Potato change
        if (potatoes == []): #If there are no images left make a new list
            allImages = []
            Makelist(dir_path)
            potatoes = allImages
        #Ok now let's actually change the image
        choice = random.randint(0, len(potatoes) - 1)
        randomImage = potatoes[choice] #Image chosen
        print(randomImage)
        potatoes.remove(randomImage)
        #Do all the stuff, resize it, etc
        im_O = Image.open(r'C:/Users/Usuario/Downloads/Experiment/'+ randomImage)
        new_image = im_O.resize((100, 100))
        potimg = ImageTk.PhotoImage(new_image)
        canvas.itemconfig(imga, image = potimg)
        canvas.image = potimg
        canvas.moveto(imga, root.winfo_screenwidth()+20, 100)
        pos = root.winfo_screenwidth()+20
    # move again after 25 ms (0.025s)
    canvas.after(25, move_imga)
#----------------------------------------------------------Starts the GUI------------------------------------------------------------
move_imga()
animation()
root.mainloop()

我尝试的做法是:当一个土豆移出屏幕时,从数组中选取一张新图片,然后打开这张图片,替换掉旧的图片,并把它传送回起始位置。但这并没有成功。我不太清楚原因,但我觉得可能是因为传送带也在使用同样的函数来更换精灵(图片)。

1 个回答

0

我尝试的方式是:当一个土豆移出屏幕时,从数组中选取一张新图片,然后我打开这张图片,修改它,再把它传送回起始位置。但这并没有成功。

你的问题可以解决。

  • 在第65和66行,把Label小部件注释掉。它们没有任何作用。
  • 在第68行,去掉关键词image = potimg,因为在第98行会更新这个值。
  • 在第74行,添加global potmig。像这样:global potatoes, potimg
  • 在第93行,把#canvas.itemconfig(imga, image = potimg)注释掉。
  • 在第98行,添加canvas.itemconfig(imga, image = potimg。把这个放在第一个if-else块之外,并且在canvas.after之前。

代码片段:

#Import
import os
import random 
from PIL import Image, ImageTk
from tkinter import Tk, Canvas, PhotoImage, NW
from tkinter import Label

# folder path
dir_path = r'C:\Users\Usuario\Downloads\Experiment'

#------------------------------------------------------------Select Random Image--------------------------------------------------------

imgExtension = ["webp","png"] #Image Extensions to be chosen from
allImages = list()

def Makelist(directory):
    for img in os.listdir(directory): #Lists all files
        ext = img.split(".")[len(img.split(".")) - 1]
        if (ext in imgExtension):
            allImages.append(img)
    return allImages

Makelist(dir_path)
global potatoes
potatoes = allImages
choice = random.randint(0, len(potatoes) - 1)
randomImage = potatoes[choice] #Image chosen
print(randomImage)
potatoes.remove(randomImage)

#------------------------------------------------------------Canvas---------------------------------------------------------------
root = Tk()
root.attributes('-transparentcolor','#f0f0f0')

canvas = Canvas(root, width = root.winfo_screenwidth(), height=300)
canvas.pack()
#-------------------------------------------------------Conveyor belt gif------------------------------------------------------------
file = r'C:\Users\Usuario\Downloads\Python\Cinta''
allImages = []
Makelist(file)
conveyor = allImages
global current_con
current_con = 0
print(conveyor)
conveyori = Image.open(file+"/"+conveyor[current_con])
conveyorimg = ImageTk.PhotoImage(conveyori)
conveyor_canva = canvas.create_image(0, 0, anchor=NW, image = conveyorimg)
conveyor_label = Label(canvas, image = conveyorimg)
conveyor_label = conveyorimg
def animation():
    global current_con
    if (current_con < 3):
        current_con += 1
    else:
        current_con = 0
    conveyori = Image.open(r'C:/Users/Usuario/Downloads/Python/Cinta/' + conveyor[current_con])
    conveyorimg = ImageTk.PhotoImage(conveyori)
    canvas.itemconfig(conveyor_canva, image = conveyorimg)
    canvas.image  = conveyorimg
    canvas.after(105, animation)
#-------------------------------------------------------------Potato a image setup------------------------------------------------------------------
im_O = Image.open(r'C:/Users/Usuario/Downloads/Experiment/' + randomImage)
new_image = im_O.resize((100, 100))
potimg = ImageTk.PhotoImage(new_image)
#potato_label = Label(canvas, image = potimg)
#potato_label = potimg
#-----------------------------------------------------Positioning the Image inside the canvas-------------------------------------------------------
imga = canvas.create_image(root.winfo_screenwidth()+20, 100, anchor=NW)
#---------------------------------------------------------------Potato a movement setup--------------------------------------------------------------
global pos
pos = root.winfo_screenwidth()+20
def move_imga():
    global pos
    global potatoes, potimg
    pos -= 5
    # move the image
    canvas.move(imga, -5, 0)
    if (pos < -90):
        #Potato change
        if (potatoes == []): #If there are no images left make a new list
            allImages = []
            Makelist(dir_path)
            potatoes = allImages
        #Ok now let's actually change the image
        choice = random.randint(0, len(potatoes) - 1)
        randomImage = potatoes[choice] #Image chosen
        print(randomImage)
        potatoes.remove(randomImage)
        #Do all the stuff, resize it, etc
        im_O = Image.open(r'C:/Users/Usuario/Downloads/Experiment/' +  randomImage)
        new_image = im_O.resize((100, 100))
        potimg = ImageTk.PhotoImage(new_image)
        #canvas.itemconfig(imga, image = potimg)
        canvas.image = potimg
        canvas.moveto(imga, root.winfo_screenwidth()+20, 100)
        pos = root.winfo_screenwidth()+20
    # move again after 25 ms (0.025s)
    canvas.itemconfig(imga, image = potimg)
    canvas.after(25, move_imga)
#----------------------------------------------------------Starts the GUI------------------------------------------------------------
move_imga()
animation()
root.mainloop()

输出:

canada.png <--- first start.
['canada-logo.png', 'canada.png', 'canada_1.png', 'canada_2.png', 'card.png', 'Chess_queen.png', 'cricket.png', 'fia_logo.png', 'guyana.png', 'laser.png', 'NOKIA.png', 'p11.png', 'p12.png', 'p13.png', 'p14.png', 'p15.png', 'p16.png', 'p17.png', 'p18.png', 'p19.png', 'p2.png', 'p20.png', 'p21.png', 'p22.png', 'p23.png', 'supra-logo.png', 'supra.png', 'turks_and_caicos.png']

You will see all outputs in below:
fia_logo.png
p19.png
p23.png
supra-logo.png
supra.png
turks_and_caicos.png
p18.png

撰写回答