gpt4 book ai didi

python - 如何使用paste()重叠两个或多个图像?

转载 作者:行者123 更新时间:2023-12-01 06:27:18 30 4
gpt4 key购买 nike

我正在为一个用 Python 编写的程序开发一个小型 GUI,该程序需要支付金额、给定金额并以纸币和硬币图像的形式返回找零。由于 tkinter 的工作原理,我正在尝试优化与笔记图像重叠的空间,但我找不到一种方法来使第二个图像不被剪切。这是我正在尝试的代码:

import tkinter as tk
from PIL import Image, ImageTk

window = tk.Tk()
window.title('main')
window.geometry('300x200')
test_image_1 = Image.open("fifty_pound.jpg")
test_image_1 = test_image_1.resize((250, 150), Image.ANTIALIAS)
test_image_2 = Image.open("twenty_pound.jpg")
test_image_2 = test_image_2.resize((250, 150), Image.ANTIALIAS)

Image.Image.paste(test_image_1, test_image_2, (50, 0))

test_image_1_render = ImageTk.PhotoImage(test_image_1)
test_image_label = tk.Label(image=test_image_1_render)
test_image_label.image = test_image_1_render
test_image_label.pack()

window.mainloop()

我得到的结果是这样的:

Image returned

如您所见,20 英镑纸币被剪掉了。我的问题是:

1)是否可以将20英镑的钞票图片与50英镑的钞票图片重叠粘贴而不被剪切?

2)如何以同样的方式重叠两张以上的图片?

非常感谢大家的帮助。

这里使用了两个图像: fifty_pound twenty_pound

最佳答案

我基本上遵循评论中给您的建议 - 但由于我已经准备了一些代码,这就是我的解决方案:

import tkinter as tk
from PIL import Image, ImageTk

# List of images (notes) to show
notes = ['fifty_pound.jpg', 'twenty_pound.jpg', 'twenty_pound.jpg']

# Same size for each note
x_note, y_note = (250, 150)

# Load images
notes = [Image.open(n).resize((x_note, y_note), Image.ANTIALIAS) for n in notes]

# Number of notes to show
n_notes = len(notes)

# Overlap (or offset) between notes
x_off, y_off = (50, 30)

# Calculate window size
window_size = (x_note + (n_notes - 1) * x_off, y_note + (n_notes - 1) * y_off)

# Create window
window = tk.Tk()
window.title('main')

# Create blank (white) image to paste notes on
new_image = Image.new('RGB', (window_size), (255, 255, 255))

# Paste notes
for i, n in enumerate(notes):
Image.Image.paste(new_image, n, (i*x_off, i*y_off))

# Rendering
new_image_render = ImageTk.PhotoImage(new_image)
test_image_label = tk.Label(image=new_image_render)
test_image_label.image = new_image_render
test_image_label.pack()

window.mainloop()

输出:

Output

希望有帮助!

----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.1
Pillow: 7.0.0
----------------------------------------

关于python - 如何使用paste()重叠两个或多个图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60074662/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com