QR二維碼目前在很多地方都有著廣泛的應用,比如微信二維碼加好友,將應用軟件的下載地址做成二維碼等等。今天我們就來看看怎麼用python生成二維碼。
1.要用python生成二維碼,首先需要下載一個python的二維碼庫,名字叫qrcode,下載地址為:https://pypi.python.org/pypi/qrcode
2. qrcode需要一個python的圖形庫,名字叫PIL。下載地址為:http://www.lfd.uci.edu/~gohlke/pythonlibs/2h39tjsk/Pillow-2.0.0.win-amd64-py2.7.exe
下載了這2個工具之後,請將他們安裝到你的機器上。qrcode用python安裝庫的方式安裝,可以是easy_install tools,也可以是把文件解壓了,然後直接用python去執行setup.py。PIL是一個exe,直接雙擊安裝即可。安裝的過程中可能會提示說找不到python2.7,那麼就需要將下面的信息保存成py文件,然後用python執行:
import sysfrom _winreg import * # tweak as necessaryversion = sys.version[:3]installpath = sys.prefix regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)installkey = "InstallPath"pythonkey = "PythonPath"pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % ( installpath, installpath, installpath) def RegisterPy(): try: reg = OpenKey(HKEY_CURRENT_USER, regpath) except EnvironmentError as e: try: reg = CreateKey(HKEY_CURRENT_USER, regpath) SetValue(reg, installkey, REG_SZ, installpath) SetValue(reg, pythonkey, REG_SZ, pythonpath) CloseKey(reg) except: print "*** Unable to register!" return print "--- Python", version, "is now registered!" return if (QueryValue(reg, installkey) == installpath and QueryValue(reg, pythonkey) == pythonpath): CloseKey(reg) print "=== Python", version, "is already registered!" return CloseKey(reg) print "*** Unable to register!" print "*** You probably have another Python installation!" if __name__ == "__main__": RegisterPy()
在必須的組件安裝完成之後,就可以開始代碼的編寫操作了。
將下面的代碼保存成py文件,用python執行即可:
import qrcodeqr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4,)qr.add_data('想要放在二維碼中的信息')qr.make(fit=True)img = qr.make_image()img.save("文件保存路徑")
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡