fillefrans
fillefrans

Reputation: 33

How can I use a variable to generate barcode with python-barcode

I'm trying to generate a barcode using python-barcode (https://github.com/WhyNotHugo/python-barcode). I manage to get a barcode generated and saved as png like this:

import barcode
from barcode.writer import ImageWriter

EAN = barcode.get_barcode_class('ean13')
ean = EAN(u'5901234123457', writer=ImageWriter())
fullname = ean.save('barcode')

However, if I try to use the value from a variable, it doesn't work:

import barcode
from barcode.writer import ImageWriter

number = 5901234123457    

EAN = barcode.get_barcode_class('ean13')
ean = EAN(number, writer=ImageWriter())
fullname = ean.save('barcode')

I then get

TypeError: 'int' object is not subscriptable

I might be making some silly mistake, but I'm quite new to this... :/

Upvotes: 3

Views: 3732

Answers (2)

Sadik Basha
Sadik Basha

Reputation: 1

from processing import *
from random import randint


def decimalToBinary(x):
    #This function converts a Decimal into a Binary
    #It generates a nibble (4 digits binary number)
    binaryNumber=bin(x)[2:]
    return (4-len(binaryNumber)) * "0" + binaryNumber

def drawBarCode(height): 
    #Generates a 13-digit bar code.
    marginLeft=30
    marginTop=40
    for i in range(1,14):  
        digit=randint(0,9)
        nibble=decimalToBinary(digit)
        for j in range(0,4):  
            if nibble[j:j+1]=="1":
                fill(0,0,0)
                stroke(0,0,0)
            else:
                fill(255,255,255)
                stroke(255,255,255)
            rect(marginLeft+i*8+2*j, marginTop, 2, height)

        #Display the digit in Decimal
        fill(0,0,0)
        stroke(0,0,0)
        #textSize(10)
        text(digit,marginLeft+i*8,marginTop+20+height)


def setup():
    strokeWeight(12)
    size(200,200)
    background(255,255,255)
    fill(0,0,0)
    stroke(0,0,0)
    drawBarCode(80)

run()

Upvotes: 0

Liam
Liam

Reputation: 6439

the barcode module only accepts strings as input, you should then just make that integer a string:

import barcode
from barcode.writer import ImageWriter

number = 5901234123457 
number = str(number)

EAN = barcode.get_barcode_class('ean13')
ean = EAN(number, writer=ImageWriter())
fullname = ean.save('barcode')

Upvotes: 4

Related Questions