Python實現的二維碼產生小軟體

來源:互聯網
上載者:User
前幾天,我估摸著做一個能產生QR Code小程式,並能用wxPython在螢幕上顯示出來。當然,我想用純Python實現,觀望了一會後,我找到了三個候選:

github 上的 python-qrcode
sourceforge上的 pyqrcode
Goolge code 上的 pyqrnative

我嘗試了python-qrcode以及pyqrnative,因為它們能夠運行在Windows/Mac/Linux。也不需要依賴額外的其他庫除了Python映像庫。pyqrcode項目需要其他一些先決條件,並且不能在Windows上運行,所以我不想與之糾纏了。我最後使用了一些以前寫過的一個Photo Viewer程式的代碼,然後稍微地修改了一下,就成了QRCode的查看器了。

開始

正如我上面提到的,你只需要Python映像庫,GUI部分我們將使用wxPython。python-qrcode相比pyqrnative產生圖片更快,並包含了你見過的大多數QR碼類型。

產生 QR Codes

當你準備好所有需要的以後,你可以運行以下代碼,看看Python做了些啥:

import osimport wx try:  import qrcodeexcept ImportError:  qrcode = None try:  import PyQRNativeexcept ImportError:  PyQRNative = None ########################################################################class QRPanel(wx.Panel):  """"""   #----------------------------------------------------------------------  def __init__(self, parent):    """Constructor"""    wx.Panel.__init__(self, parent=parent)    self.photo_max_size = 240    sp = wx.StandardPaths.Get()    self.defaultLocation = sp.GetDocumentsDir()     img = wx.EmptyImage(240,240)    self.imageCtrl = wx.StaticBitmap(self, wx.ID_ANY,                     wx.BitmapFromImage(img))     qrDataLbl = wx.StaticText(self, label="Text to turn into QR Code:")    self.qrDataTxt = wx.TextCtrl(self, value="http://www.mousevspython.com", size=(200,-1))    instructions = "Name QR image file"    instructLbl = wx.StaticText(self, label=instructions)    self.qrPhotoTxt = wx.TextCtrl(self, size=(200,-1))    browseBtn = wx.Button(self, label='Change Save Location')    browseBtn.Bind(wx.EVT_BUTTON, self.onBrowse)    defLbl = "Default save location: " + self.defaultLocation    self.defaultLocationLbl = wx.StaticText(self, label=defLbl)     qrcodeBtn = wx.Button(self, label="Create QR with qrcode")    qrcodeBtn.Bind(wx.EVT_BUTTON, self.onUseQrcode)    pyQRNativeBtn = wx.Button(self, label="Create QR with PyQRNative")    pyQRNativeBtn.Bind(wx.EVT_BUTTON, self.onUsePyQR)     # Create sizer    self.mainSizer = wx.BoxSizer(wx.VERTICAL)    qrDataSizer = wx.BoxSizer(wx.HORIZONTAL)    locationSizer = wx.BoxSizer(wx.HORIZONTAL)    qrBtnSizer = wx.BoxSizer(wx.VERTICAL)     qrDataSizer.Add(qrDataLbl, 0, wx.ALL, 5)    qrDataSizer.Add(self.qrDataTxt, 1, wx.ALL|wx.EXPAND, 5)    self.mainSizer.Add(wx.StaticLine(self, wx.ID_ANY),              0, wx.ALL|wx.EXPAND, 5)    self.mainSizer.Add(qrDataSizer, 0, wx.EXPAND)    self.mainSizer.Add(self.imageCtrl, 0, wx.ALL, 5)    locationSizer.Add(instructLbl, 0, wx.ALL, 5)    locationSizer.Add(self.qrPhotoTxt, 0, wx.ALL, 5)    locationSizer.Add(browseBtn, 0, wx.ALL, 5)    self.mainSizer.Add(locationSizer, 0, wx.ALL, 5)    self.mainSizer.Add(self.defaultLocationLbl, 0, wx.ALL, 5)     qrBtnSizer.Add(qrcodeBtn, 0, wx.ALL, 5)    qrBtnSizer.Add(pyQRNativeBtn, 0, wx.ALL, 5)    self.mainSizer.Add(qrBtnSizer, 0, wx.ALL|wx.CENTER, 10)     self.SetSizer(self.mainSizer)    self.Layout()   #----------------------------------------------------------------------  def onBrowse(self, event):    """"""    dlg = wx.DirDialog(self, "Choose a directory:",              style=wx.DD_DEFAULT_STYLE)    if dlg.ShowModal() == wx.ID_OK:      path = dlg.GetPath()      self.defaultLocation = path      self.defaultLocationLbl.SetLabel("Save location: %s" % path)    dlg.Destroy()   #----------------------------------------------------------------------  def onUseQrcode(self, event):    """    https://github.com/lincolnloop/python-qrcode    """    qr = qrcode.QRCode(version=1, box_size=10, border=4)    qr.add_data(self.qrDataTxt.GetValue())    qr.make(fit=True)    x = qr.make_image()     qr_file = os.path.join(self.defaultLocation, self.qrPhotoTxt.GetValue() + ".jpg")    img_file = open(qr_file, 'wb')    x.save(img_file, 'JPEG')    img_file.close()    self.showQRCode(qr_file)   #----------------------------------------------------------------------  def onUsePyQR(self, event):    """http://code.google.com/p/pyqrnative/    """    qr = PyQRNative.QRCode(20, PyQRNative.QRErrorCorrectLevel.L)    qr.addData(self.qrDataTxt.GetValue())    qr.make()    im = qr.makeImage()     qr_file = os.path.join(self.defaultLocation, self.qrPhotoTxt.GetValue() + ".jpg")    img_file = open(qr_file, 'wb')    im.save(img_file, 'JPEG')    img_file.close()    self.showQRCode(qr_file)   #----------------------------------------------------------------------  def showQRCode(self, filepath):    """"""    img = wx.Image(filepath, wx.BITMAP_TYPE_ANY)    # scale the image, preserving the aspect ratio    W = img.GetWidth()    H = img.GetHeight()    if W > H:      NewW = self.photo_max_size      NewH = self.photo_max_size * H / W    else:      NewH = self.photo_max_size      NewW = self.photo_max_size * W / H    img = img.Scale(NewW,NewH)     self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))    self.Refresh()  ########################################################################class QRFrame(wx.Frame):  """"""   #----------------------------------------------------------------------  def __init__(self):    """Constructor"""    wx.Frame.__init__(self, None, title="QR Code Viewer", size=(550,500))    panel = QRPanel(self) if __name__ == "__main__":  app = wx.App(False)  frame = QRFrame()  frame.Show()  app.MainLoop()

python-qrcode產生:

PyQRNative產生:

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.