无法获取Tkinter Entry值作为图片文件名 报'Application'无'txt'属性
报错原因
你在__init__方法中创建的输入框txt是局部变量,未绑定为Application类的实例属性,类内其他方法无法通过self.txt访问该组件,因此触发'Application'对象没有'txt'属性的报错。
修正步骤
- 将输入框初始化语句从
txt = tk.Entry(self.root,width=10)修改为self.txt = tk.Entry(self.root,width=10),把组件绑定到类实例,供类内所有方法调用 - 统一图片保存的后缀和格式参数:原代码文件名后缀为
.jpg,但保存方法传入的是png格式,需保持一致避免文件损坏 - 增加空输入兜底逻辑:用户未输入名称时自动生成默认文件名,避免空文件名报错
- 补充摄像头帧类型适配:如果
self.current_image是OpenCV读取的摄像头帧(numpy数组格式),不能直接调用PIL的save方法,需替换为OpenCV的写入接口
修正后关键代码片段
__init__方法内的输入框初始化
# 原局部变量改为实例属性 self.txt = tk.Entry(self.root,width=10) self.txt.pack(fill="both", expand=True, padx=5, pady=5)
take_snapshot方法修正
def take_snapshot(self): """ Take snapshot and save it to the file """ # 获取输入内容并去除首尾空格 img_name = self.txt.get().strip() # 空输入兜底:用时间戳生成默认文件名 if not img_name: from datetime import datetime img_name = f"capture_{datetime.now().strftime('%Y%m%d_%H%M%S')}" filename = f"{img_name}.jpg" p = os.path.join(self.output_path, filename) # 若为OpenCV读取的帧,替换为cv2.imwrite(p, self.current_image) self.current_image.save(p, "jpeg") print("[INFO] saved {}".format(filename))
注意:如果后续运行出现类型错误,大概率是
self.current_image的类型和保存方法不匹配:仅PIL.Image对象支持调用.save()方法,OpenCV读取的摄像头帧是numpy数组,必须用cv2.imwrite(文件路径, 帧数据)来保存。
内容的提问来源于stack exchange,提问作者Axen_Rangs
相关产品推荐
相关产品推荐

