【问题标题】:How can I use a variable to generate barcode with python-barcode如何使用变量生成带有 python-barcode 的条形码
【发布时间】:2019-01-20 10:44:58
【问题描述】:

我正在尝试使用 python-barcode (https://github.com/WhyNotHugo/python-barcode) 生成条形码。我设法生成一个条形码并保存为 png,如下所示:

import barcode
from barcode.writer import ImageWriter

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

但是,如果我尝试使用变量中的值,它就不起作用:

import barcode
from barcode.writer import ImageWriter

number = 5901234123457    

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

然后我得到

TypeError: 'int' object is not subscriptable

我可能会犯一些愚蠢的错误,但我对此很陌生...:/

【问题讨论】:

    标签: python barcode


    【解决方案1】:

    条形码模块只接受字符串作为输入,然后您应该将该整数设为字符串:

    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')
    

    【讨论】:

      【解决方案2】:
      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()
      

      【讨论】:

        猜你喜欢
        • 2014-10-16
        • 2019-12-05
        • 1970-01-01
        • 2016-08-02
        • 1970-01-01
        • 2018-05-11
        • 1970-01-01
        • 2020-03-27
        • 2011-06-09
        相关资源
        最近更新 更多