
問題背景最近在運行一個Python 二維碼生成器程序時遇到如下報錯(venv)E:\projects\GithubProjects\mosh-hamedani\python-projects-for-beginnerspython qr_code_generator.py Enter the text or URL: https://codewithmosh.com Enter the filename: mosh.jpg Traceback(most recent call last): FileE:\projects\GithubProjects\mosh-hamedani\python-projects-for-beginners\qr_code_generator.py, line7,inmoduleimageqr.make_image(fill_colorblack,back_colorwhite)FileE:\projects\GithubProjects\mosh-hamedani\python-projects-for-beginners\venv\Lib\site-packages\qrcode\main.py, line364,inmake_image from qrcode.image.pilimportImage, PilImage FileE:\projects\GithubProjects\mosh-hamedani\python-projects-for-beginners\venv\Lib\site-packages\qrcode\image\pil.py, line2,inmodulefrom PILimportImage, ImageDraw ModuleNotFoundError: No module namedPIL原因是缺少了Pillow包在https://stackoverflow.com/questions/8863917/importerror-no-module-named-pil這里找到了原因。按照這篇文章的意思PIL包已經(jīng)過時使用https://pypi.org/project/pillow/替代截止目前最新版本是 12.3.0源代碼地址為https://github.com/mosh-hamedani/python-projects-for-beginners/blob/main/qr_code_generator.py 來自Mosh大神的示例代碼。功能是輸入網(wǎng)址和圖片名稱然后再借助qrcode生成網(wǎng)址的二維碼。Python代碼如下importqrcode datainput(Enter the text or URL: ).strip()filenameinput(Enter the filename: ).strip()qrqrcode.QRCode(box_size10,border4)qr.add_data(data)imageqr.make_image(fill_colorblack,back_colorwhite)image.save(filename)print(fQR code saved as{filename})將上述代碼保存為qr_code_generator.py文件然后在安裝了Python 3.14.4 的Window11機器上打開cmd命令行終端輸入如下命令安裝qrcode包pipinstallqrcode安裝之后再輸入python qr_code_generator.py運行程序報錯如下再次運行程序成功生成二維碼圖片手機掃描上述二維碼之后就可以訪問https://codewithmosh.com 這個網(wǎng)站了當然我們還可以根據(jù)自己的文本生成其他內(nèi)容。參考資料python-projects-for-beginners Github倉庫源代碼python-projects-for-beginners[mosh python-projects-for-beginners視頻地址: Python Projects for Beginners – Master Problem-Solving! https://pypi.org/project/qrcode/https://pypi.org/project/pillow/