import barcode
import logging
from barcode.codex import Code128
from barcode.writer import ImageWriter
from PIL import Image, ImageDraw, ImageFont
import tkinter as tk
from tkinter import filedialog, messagebox
from pathlib import Path
def generate_barcode_image(url):
bar = Code128(url, writer=ImageWriter())
img = bar.render()
img = img.rotate(0)
img = img.resize((img.width // 2, img.height // 2))
draw = ImageDraw.Draw(img)
return img
def arrange_images(images_list, save_path):
A4_WIDTH_PIXELS = 2480
A4_HEIGHT_PIXELS = 3508
AQR_CODE_PADDING_LEFT = 120
AQR_CODE_PADDING_TOP = 200
image_count = len(images_list)
for i in range(image_count):
image = images_list[i]
images_per_row = min(5, image_count)
rows = int(image_count / images_per_row) + int(bool(image_count % images_per_row))
margin_left =150
margin_top = 150
a4_paper = Image.new("RGB", (A4_WIDTH_PIXELS, A4_HEIGHT_PIXELS), "white")
x_offset, y_offset = margin_left, margin_top
for i, image in enumerate(images_list):
image_path = image['path']
bar_code_img = Image.open(image_path)
resized_bar_code_img = bar_code_img.resize((400, 250))
a4_paper.paste(resized_bar_code_img, (x_offset, y_offset))
if (i + 1) % images_per_row == 0:
x_offset = margin_left
y_offset += 300 + margin_top
else:
x_offset += 300 + margin_left
a4_paper.save(save_path)
def select_txt_files():
txt_files_str = filedialog.askopenfilenames(filetypes=(("Text Files", "*.txt"), ("All files", "*.*")))
txt_files_entry.delete(0, tk.END)
txt_files_entry.insert(tk.END, ",".join(txt_files_str))
generate_button = tk.Button(frame1, text="生成条码",command=generate_bar_code)
generate_button.grid(row=0, column=3, padx=5)
return txt_files_str
def generate_bar_code():
txt_file_paths = txt_files_entry.get().split(",")
barcode_images = []
counter = 1
for file_path in txt_file_paths:
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()[:30]
for line in lines:
content = line.strip()
if not content:
continue
try:
image_dict = {}
image_dict['url'] = content
image_dict['path'] = f"bar_code_{counter}.jpg"
img = generate_barcode_image(content)
img.save(image_dict['path'], "JPEG", quality=100)
barcode_images.append(image_dict)
counter += 1
except Exception as e:
logging.error(f"处理内容时出现错误:{content}。错误信息:{str(e)}")
if len(barcode_images) > 0:
save_path = filedialog.asksaveasfilename(defaultextension='.jpg', filetypes=(("JPEG Files", "*.jpg"), ("All files", "*.*")))
arrange_images(barcode_images, save_path)
messagebox.showinfo('完成', '条码生成完毕,打开图片查看吧~~')
for image_dict in barcode_images:
bar_code_file = image_dict['path']
bar_code_path = Path(bar_code_file)
if bar_code_path.exists():
bar_code_path.unlink()
else:
messagebox.showinfo('提示','TXT文件格式不正确,请确保文档内容不为空')
if __name__ == "__main__":
root = tk.Tk()
root.title("批量生成条码")
frame1 = tk.Frame(root)
frame1.pack(pady=30)
txt_label = tk.Label(frame1, text="要处理的TXT文件列表:")
txt_label.grid(row=0, column=0, padx=10)
txt_files_entry = tk.Entry(frame1, width=80)
txt_files_entry.grid(row=0, column=1, padx=10)
txt_button = tk.Button(frame1, text="选择文件", command=select_txt_files)
txt_button.grid(row=0, column=2, padx=10)
root.mainloop()