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

Tkinter项目中同目录图片无法识别的问题求助

坎耶语录应用图片加载问题解决办法

问题场景

开发坎耶语录应用,代码如下:

from tkinter import *
import requests


def get_quote():
    response = requests.get(url="https://api.kanye.rest")
    response.raise_for_status()
    data = response.json()
    quote = data["quote"]
    canvas.itemconfig(quote_text, text=quote)


window = Tk()
window.title("Kanye Says...")
window.config(padx=50, pady=50)

canvas = Canvas(width=300, height=414)
background_img = PhotoImage(file="background.png")
canvas.create_image(150, 207, image=background_img)
quote_text = canvas.create_text(150, 207, text="Kanye Quote Goes HERE", width=250, font=("Arial", 30, "bold"),
                                fill="black")
canvas.grid(row=0, column=0)

kanye_img = PhotoImage(file="kanye.png")
kanye_button = Button(image=kanye_img, highlightthickness=0, command=get_quote)
kanye_button.grid(row=1, column=0)

window.mainloop()

图片与代码文件在同一文件夹内,但点击按钮时提示图片不存在,已尝试移出移入、重命名图片,图片可正常打开但无法被程序识别,且无法重新下载原图。

解决办法

  • 确认运行时工作目录:Python脚本运行的工作目录可能并非脚本所在文件夹,在代码开头添加以下代码查看当前工作目录:

    import os
    print(os.getcwd())
    

    如果输出路径不是图片所在文件夹,可手动切换到该目录后再运行脚本,或改用绝对路径加载图片。

  • 使用绝对路径加载图片:通过脚本所在目录的绝对路径拼接图片路径,确保无论脚本在哪里运行都能找到图片,修改图片加载代码如下:

    import os
    script_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 加载背景图
    background_img = PhotoImage(file=os.path.join(script_dir, "background.png"))
    # 加载坎耶按钮图
    kanye_img = PhotoImage(file=os.path.join(script_dir, "kanye.png"))
    
  • 检查文件实际扩展名:部分系统默认隐藏文件扩展名,可能存在图片实际名为background.png.jpg但显示为background.png的情况,开启文件夹“显示文件扩展名”选项,确认文件名与代码中一致。

  • 检查文件读取权限:确保当前用户对图片文件有读取权限,Windows系统可右键图片文件→属性→安全,确认当前用户拥有读取权限,必要时修改权限设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:10:32