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

如何用Python创建实时显示微电路染色变化的交互式窗口?

实现微电路依次染色的交互式窗口(Tkinter方案)

需求说明

现有两张图片:一张是5个普通微电路,另一张是5个全蓝色微电路。需要实现一个Python交互式窗口,每次触发操作(点击按钮)时,依次将第1、2…5个微电路染成蓝色,最终显示全蓝效果。

实现步骤

1. 依赖安装

先安装图片处理所需的库:

pip install pillow

2. 代码实现

将两张图片分别保存为original_chips.png(普通微电路)和blue_chips.png(全蓝微电路),放在代码同目录下,运行以下代码:

import tkinter as tk
from PIL import Image, ImageTk

# 初始化主窗口
root = tk.Tk()
root.title("微电路染色演示")

# 加载原始和蓝色图片
original_img = Image.open("original_chips.png")
blue_img = Image.open("blue_chips.png")

# 计算单个微电路的区域(假设5个芯片横向等宽排列)
chip_width = original_img.width // 5
chip_height = original_img.height

current_colored = 0  # 当前已染色的芯片数量

def generate_current_image():
    """生成当前状态的图片:前current_colored个为蓝色,其余为原始状态"""
    current_img = Image.new("RGB", original_img.size)
    for idx in range(5):
        left = idx * chip_width
        right = (idx + 1) * chip_width
        # 选择对应状态的芯片区域
        source_img = blue_img if idx < current_colored else original_img
        chip = source_img.crop((left, 0, right, chip_height))
        current_img.paste(chip, (left, 0))
    return current_img

def color_next():
    """染色下一个微电路,并更新窗口显示"""
    global current_colored, tk_image, img_label
    if current_colored < 5:
        current_colored += 1
        # 更新图片并刷新显示
        updated_img = generate_current_image()
        tk_image = ImageTk.PhotoImage(updated_img)
        img_label.config(image=tk_image)
    else:
        print("所有微电路已完成染色")

# 初始化显示原始图片
tk_image = ImageTk.PhotoImage(original_img)
img_label = tk.Label(root, image=tk_image)
img_label.pack(pady=10)

# 添加交互按钮
color_btn = tk.Button(root, text="染色下一个微电路", command=color_next)
color_btn.pack(pady=5)

# 启动主循环
root.mainloop()

代码说明

  • 用tkinter搭建交互式窗口,通过按钮触发染色逻辑
  • 借助Pillow完成图片的裁剪与合成,每次点击按钮生成对应状态的图片并更新窗口显示
  • 默认假设两张图片中5个微电路横向等宽排列,若实际布局不同,可调整chip_width计算方式或手动指定每个芯片的区域坐标

内容的提问来源于stack exchange,提问作者MicrolaB-RCR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:25:11