本帖最后由 TZ425 于 2023-11-2 03:26 编辑
功能:
选择一张图片进行 N*N 分割
[Python] 纯文本查看 复制代码 import tkinter as tk
from tkinter import filedialog
from PIL import Image
class App:
def __init__(self, master):
self.master = master
master.title("图片切割程序")
self.label1 = tk.Label(master, text="切割的图片:")
self.label1.grid(row=0, column=0)
self.entry1 = tk.Entry(master)
self.entry1.grid(row=0, column=1)
self.button1 = tk.Button(master, text="选 择 文 件", command=self.select_file)
self.button1.grid(row=0, column=2)
self.label2 = tk.Label(master, text="保存的路径:")
self.label2.grid(row=1, column=0)
self.entry2 = tk.Entry(master)
self.entry2.grid(row=1, column=1)
self.button2 = tk.Button(master, text="选择文件夹", command=self.select_folder)
self.button2.grid(row=1, column=2)
self.label3 = tk.Label(master, text="切割后生成横排的数量:")
self.label3.grid(row=2, column=0)
self.entry3 = tk.Entry(master)
self.entry3.grid(row=2, column=1)
self.label4 = tk.Label(master, text="切割后生成的纵列数量:")
self.label4.grid(row=3, column=0)
self.entry4 = tk.Entry(master)
self.entry4.grid(row=3, column=1)
self.button3 = tk.Button(master, text="开始切割", command=self.start_cutting)
self.button3.grid(row=4, column=1)
self.button4 = tk.Button(master, text="退出", command=master.quit)
self.button4.grid(row=5, column=1)
self.rows = 0
self.columns = 0
def select_file(self):
file_path = filedialog.askopenfilename()
self.entry1.delete(0, tk.END)
self.entry1.insert(0, file_path)
def select_folder(self):
folder_path = filedialog.askdirectory()
self.entry2.delete(0, tk.END)
self.entry2.insert(0, folder_path)
def start_cutting(self):
file_path = self.entry1.get()
folder_path = self.entry2.get()
rows = int(self.entry3.get())
columns = int(self.entry4.get())
try:
image = Image.open(file_path)
width, height = image.size
cell_width = width // columns
cell_height = height // rows
for i in range(rows):
for j in range(columns):
left = j * cell_width
upper = i * cell_height
right = left + cell_width
lower = upper + cell_height
cropped_image = image.crop((left, upper, right, lower))
save_path = folder_path + f"/{i}_{j}.png" # 保存为PNG格式,可根据需要修改
cropped_image.save(save_path)
print("图片切割完成!")
except Exception as e:
print("发生错误:", e)
root = tk.Tk()
app = App(root)
root.mainloop() |