You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:开发二维码生成器时遇AttributeError,Image无open属性

解决AttributeError: type object 'Image' has no attribute 'open'问题

报错原因

你使用了from tkinter import *,而tkinter库本身包含一个Image类,和PIL库的Image重名,导致调用Image.open()时实际调用的是tkinter的Image类,它并没有open方法。

修改步骤

  • 替换通配符导入方式,改用import tkinter as tk,彻底避免命名冲突
  • 给输入框添加引用,获取用户输入的内容(原代码未获取输入,生成的是空二维码)
  • 生成二维码时补充数据添加和编码步骤(原代码缺少add_data和make操作)
  • 将PIL图片转换为tkinter支持的格式,在窗口中显示生成的二维码

修改后的完整代码

import qrcode
from PIL import Image, ImageTk
import tkinter as tk

root = tk.Tk()
root.geometry('500x500')
root.title('QR Code Generator Application')
root.resizable(0,0)

tk.Label(root, text='QR Code Generator Application', font='Helvetica 18 bold').place(x=65, y=20)
tk.Label(root, text='Enter anything into the input field: ', font='Helvetica 12').place(x=20, y=90)

# 给输入框添加引用,方便后续获取内容
input_entry = tk.Entry(root, width=25)
input_entry.place(x=250, y=93)

# 用于显示二维码的Label容器
qr_label = tk.Label(root)
qr_label.place(x=150, y=200)

def button():
    # 获取输入框内容并去除首尾空格
    input_text = input_entry.get().strip()
    if not input_text:
        return  # 空输入时不执行生成逻辑
    
    qr_code = qrcode.QRCode(version=2, box_size=10, border=4)
    qr_code.add_data(input_text)  # 加入要编码的内容
    qr_code.make(fit=True)  # 完成二维码编码
    
    img = qr_code.make_image(fill='Black', back_color='Red')
    img.save('QR_Code_1.png')
    
    # 将PIL图片转换为tkinter可识别的格式
    tk_img = ImageTk.PhotoImage(Image.open('QR_Code_1.png'))
    qr_label.config(image=tk_img)
    qr_label.image = tk_img  # 保留图片引用,防止被垃圾回收导致图片不显示

tk.Button(root, text='Generate', font='Helvetica 15 bold', bg='Green', command=button).place(x=183, y=140)
root.mainloop()

关键修改说明

  1. 用import tkinter as tk替代通配符导入,从根源解决命名冲突问题
  2. 新增input_entry引用输入框,实现用户输入内容的获取
  3. 添加qr_label作为二维码的显示容器,转换后的图片需要手动保留引用,否则会被Python垃圾回收机制清理,导致窗口中无法显示图片
  4. 增加空输入判断,避免生成无意义的空二维码

内容的提问来源于stack exchange,提问作者CodeMaster74

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:55:11