You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现图片淡入淡出切换报错:can't multiply sequence by non-int of type 'float'

解决图片淡入淡出过渡中的can't multiply sequence by non-int of type 'float'错误

错误原因

你遇到的报错是因为getpixel()返回的是RGB像素的三元组(比如(255, 128, 64)),Python不允许直接用浮点数去乘整个元组序列,必须对每个颜色通道单独计算混合值。

修复代码

重点修改ob_Fade函数中的像素计算逻辑,逐个通道计算加权混合值后转成整数(像素值必须是0-255的整数):

import tkinter as tk
from PIL import ImageTk, Image

root = tk.Tk()

root.geometry('300x300')
root.resizable(width=True, height=True)

image1 = Image.open('name.jpg')
image2 = Image.open('name.png')

width = min(image1.width, image2.width)
height = min(image1.height, image2.height)

# 新版Pillow中ANTIALIAS已废弃,改用LANCZOS
image1 = image1.resize((width, height), Image.Resampling.LANCZOS)
image2 = image2.resize((width, height), Image.Resampling.LANCZOS)

def ob_Fade(image1, image2, d):
    new_image = Image.new('RGB', (image1.width, image1.height), color='white')
    for x in range(image1.width):
        for y in range(image1.height):
            pixel_1 = image1.getpixel((x, y))
            pixel_2 = image2.getpixel((x, y))
            # 对RGB三个通道分别计算加权混合值,转换为整数
            r = int(d * pixel_1[0] + (1 - d) * pixel_2[0])
            g = int(d * pixel_1[1] + (1 - d) * pixel_2[1])
            b = int(d * pixel_1[2] + (1 - d) * pixel_2[2])
            new_image.putpixel((x, y), (r, g, b))
    return new_image

# 提前创建Label,避免每次循环重复创建
image_label = tk.Label(root)
image_label.grid(row=2, column=1)

def start():
    # 循环到101才能让d=1.0,实现完全过渡到image1
    for i in range(0, 101):
        d = i / 100
        image = ob_Fade(image1, image2, d)
        image = image.resize((250, 250), Image.Resampling.LANCZOS)
        photo = ImageTk.PhotoImage(image)
        image_label.config(image=photo)
        image_label.image = photo  # 保留引用防止图片被垃圾回收
        root.update()

done = tk.Button(root, text="DO", padx=1, pady=0, command=start) 
done.grid(row=0, column=1) 
root.mainloop()

额外优化说明

  1. 废弃API替换:Image.ANTIALIAS在Pillow 9.1.0之后已被标记为废弃,改用Image.Resampling.LANCZOS实现高质量缩放。
  2. 复用Label组件:提前创建一个Label,循环中仅更新其image属性,避免重复创建组件带来的性能损耗。
  3. 循环范围调整:将range(0,100)改为range(0,101),确保d能达到1.0,实现完全过渡到image1的效果。

内容的提问来源于stack exchange,提问作者Sinkos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:31:04