首页 > 解决方案 > pyqrcode.create 不存在

问题描述

我正在尝试将二维码合并到 pdf 中。当我将代码分成两个单独的脚本时,它工作正常。我是 phython 的新手,任何帮助都将不胜感激。我在 Phyton 2.7 的 RHEL 7.4 上运行它是的,我知道它很旧,但它是第 3 方服务器,我无法升级它。

[user@myserver scripts]$ python pdf_test3.py
Traceback (most recent call last):
  File "pdf_test3.py", line 28, in <module>
    qcode = pyqrcode("http://www.weather.com","/cfg/test.png")
  File "pdf_test3.py", line 8, in __init__
    qrCode = self.create(url)
AttributeError: pyqrcode instance has no attribute 'create'
from fpdf import FPDF
from pyqrcode import QRCode
import png
import sys

class pyqrcode(QRCode):
    def __init__(self, url,fileOutputDir):
        qrCode = self.create(url)
        # create qr code and save it as a svg image
        qrCode.png(fileOutputDir, scale=1)

class PDF(FPDF):
    def __init__(self,imageFileName):
        # file name, left,top,heght,width
        self.image(imageFileName, 200,1,20,20)
        self.cell(30, 10, 'Title', 1, 0, 'C')

    # Page footer
    def footer(self):
        # Position at 1.5 cm from bottom
        self.set_y(-15)
        # Arial italic 8
        self.set_font('Arial', 'I', 8)
        # Page number
        self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')

# Instantiation of inherited class
qcode = pyqrcode("http://www.weather.com","/cfg/test.png")

pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Times', '', 12)
for i in range(1, 5):
    pdf.cell(0, 10, 'Hello World.' + str(i), 0, 1)
pdf.output('test.pdf', 'F')

标签: pythonpython-2.7

解决方案


您的错误是说您自己的pyqrcode实例没有创建功能,但它没有。另外,最好不要用与模块同名的类来命名

您可以通过导入 create 函数来解决这个问题

from fpdf import FPDF
from pyqrcode import QRCode
from pyqrcode import create as create_qrcode
import png
import sys

class PyQRcode(QRCode):
    def __init__(self, url,fileOutputDir):
        qrCode = create_qrcode(url)

推荐阅读