Today, I'd like to introduce to you a particularly practical Python library—python-barcode
. Whether you're working on retail systems, inventory management, or ticket printing, this library can help you easily generate various barcodes. Why choose python-barcode
? In development, we often need to generate barcodes, but many tools on the market are either too complex or charge fees. python-barcode
is not only open-source and free but also particularly easy to use, supporting various common barcode formats such as EAN-13, EAN-8, Code128, etc.
Quick Start Let's install this library:
pip install python-barcode
If you need to generate barcodes in PNG format, you also need to install Pillow:
pip install Pillow
Basic Usage Let's look at the most basic usage:
from barcode import generate
from barcode.writer import ImageWriter
# Generate an EAN-13 barcode
# Note: EAN-13 requires 12 digits, and the last one will be calculated as the check digit automatically
number = '123456789012'
generate('ean13', number, ImageWriter(), 'product_code')
It's that simple, and a barcode is generated! The generated file will be automatically saved as product_code.png
.
Advanced Features
Generate different types of barcodes
from barcode import Code128, Code39, EAN13
from barcode.writer import ImageWriter
def generate_different_codes():
# Generate a Code128 barcode (suitable for alphanumeric mixed)
code128 = Code128('PYTHON2024', writer=ImageWriter())
code128.save('inventory_code')
# Generate a Code39 barcode (suitable for alphanumeric and special characters)
code39 = Code39('PROD-123', writer=ImageWriter())
code39.save('product_id')
# Generate an EAN13 barcode (suitable for product coding)
ean13 = EAN13('123456789012', writer=ImageWriter())
ean13.save('barcode_ean13')
generate_different_codes()
Customize barcode styles
from barcode import Code128
from barcode.writer import ImageWriter
def create_custom_barcode():
# Create custom options
writer = ImageWriter()
# Set barcode options
options = {
'module_height': 15.0, # Barcode height
'module_width': 0.8, # Barcode width
'quiet_zone': 6.0, # Quiet zone width on both sides
'font_size': 12, # Font size
'text_distance': 5.0, # Distance between text and barcode
}
# Generate the barcode
code = Code128('CUSTOM-2024', writer=writer)
code.save('styled_barcode', options)
create_custom_barcode()
Real-world example: Small Warehouse Management System Let's look at a practical application scenario:
from barcode import Code128
from barcode.writer import ImageWriter
import random
import string
from datetime import datetime
class WarehouseLabeler:
def __init__(self):
self.writer = ImageWriter()
def generate_item_code(self, category, item_id):
"""Generate product barcode"""
timestamp = datetime.now().strftime("%Y%m%d")
code = f"{category}-{item_id}-{timestamp}"
barcode = Code128(code, writer=self.writer)
filename = f"item_{category}_{item_id}"
barcode.save(filename)
return filename
def create_batch_labels(self, category, count):
"""Generate labels in batch"""
results = []
for i in range(count):
# Generate a random item ID
item_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
filename = self.generate_item_code(category, item_id)
results.append((item_id, filename))
return results
# Usage example
labeler = WarehouseLabeler()
# Generate 5 labels for the electronics category
electronics_labels = labeler.create_batch_labels("ELEC", 5)
for item_id, filename in electronics_labels:
print(f"Generated label: Item ID {item_id}, Filename {filename}")
Special Tips Barcode type selection suggestions:
EAN-13: Suitable for retail products Code128: Suitable for logistics tracking Code39: Suitable for industrial applications ISBN: Suitable for book encoding
Notes for generating barcodes:
Ensure input data complies with format requirements Pay attention to image resolution and printing quality Reserve enough blank space
Common problem solutions:
Check digit error: Use the get_fullcode()
method to view the complete encoding
from barcode import EAN13
code = EAN13('123456789012')
print(f"Complete barcode (including check digit): {code.get_fullcode()}")
Image quality adjustment:
from barcode import Code128
from barcode.writer import ImageWriter
# Improve image quality
writer = ImageWriter()
writer.dpi = 300 # Increase DPI
code = Code128('HIGH-QUALITY', writer=writer)
code.save('high_quality_barcode')
Tips:
In a production environment, it is recommended to handle exceptions properly Regularly test whether the generated barcodes can be scanned correctly Reasonably set the size of the barcode to ensure readability Remember to back up important barcode data
Folks, that's it for today's barcode generation tool introduction! If you have any questions, feel free to ask in the comments. Remember, barcodes may be small, but they are a great help in practical applications!