Tkinter导入图片失败求助:_tkinter.TclError报错
Tkinter登录页面图片报错问题解决
错误原因
- Tkinter的Label组件不支持直接使用PIL的
Image对象,必须转成ImageTk.PhotoImage格式才能识别。 - 单反斜杠路径会触发Python转义字符解析,导致图片路径识别错误。
- 代码中
login函数后存在多余的else块,属于语法错误。 - 图片对象未保留引用时,会被Python垃圾回收机制回收,导致图片无法显示。
修改后的完整代码
import tkinter as tk from PIL import ImageTk, Image from tkinter import messagebox def login(name, pwd): if len(name) == 0: messagebox.showinfo(title="Authentication", message="Enter Username") elif len(pwd) == 0: messagebox.showinfo(title="Authentication", message="Enter Password") elif name == 'admin' and pwd == 'p4$$w0Rd': messagebox.showinfo(title="Authentication", message="Woohoo! Sucessfully authenticated and logged in :D !") else: messagebox.showinfo(title="Authentication", message="Oh no! Failed to Authenicate and Login D: !") root = tk.Tk() root.geometry("400x300") root.title("Krypton OS Login Page") # 处理背景图:转换格式+保留引用 bg_image = Image.open("Apps/Login/wallpaper.jpg") # 用正斜杠避免转义问题 bg = ImageTk.PhotoImage(bg_image) bg_label = tk.Label(root, image=bg) bg_label.place(x=0, y=0) bg_label.image = bg # 绑定引用防止被垃圾回收 # 处理Logo图:转换格式+保留引用 logo_image = Image.open("Apps/Login/Login.jpg") # logo_image = logo_image.resize((70, 70)) # 需要缩放时取消注释 rgb_logo = logo_image.convert("RGB") rgb_logo.save("Login.jpg") # 不需要保存转换后的图片可删除此行 logo_photo = ImageTk.PhotoImage(logo_image) logo_label = tk.Label(root, image=logo_photo) logo_label.place(x=150, y=30) logo_label.image = logo_photo # 绑定引用防止被垃圾回收 # 用户名输入区域 label2 = tk.Label(root, text="User Name", font=(10)) label2.place(x=50, y=120) name_var = tk.StringVar() uname = tk.Entry(root, textvariable=name_var, width=15, font=(10)) uname.place(x=160, y=120) # 密码输入区域 label3 = tk.Label(root, text="Password", font=(10)) label3.place(x=50, y=160) pwd_var = tk.StringVar() pwd = tk.Entry(root, textvariable=pwd_var, width=15, font=(10), show="*") pwd.place(x=160, y=160) # 登录按钮 B = tk.Button(root, text="LOGIN", width=15, fg="red", bg="black", command=lambda: login(name_var.get(), pwd_var.get())) B.place(x=160, y=210) root.mainloop()
核心修改说明
- 图片格式转换:将Logo的PIL
Image对象通过ImageTk.PhotoImage()转换成Tkinter支持的格式,再传入Label组件。 - 路径修正:把路径中的单反斜杠
\替换为正斜杠/,避免转义字符导致的路径错误。 - 语法修复:删除
login函数后多余的else块,合并条件判断简化逻辑。 - 保留图片引用:将PhotoImage对象绑定到对应Label组件的
image属性上,防止垃圾回收导致图片消失。
内容的提问来源于stack exchange,提问作者TheManBehindTheComputer101
相关产品推荐
相关产品推荐

