为什么Python的Tkinter Image函数无法定位PNG文件?

问题描述 投票:0回答:1
Traceback (most recent call last):
  File "c:\Users\####\Desktop\Python_Demo_Projects\Quiz_Program\problematic.py", line 51, in <module>
    previous_slide()
  File "c:\Users\####\Desktop\Python_Demo_Projects\Quiz_Program\problematic.py", line 43, in previous_slide
    temp_graphic = Image(resource_path(graphic))
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\tkinter\__init__.py", line 4097, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: image type "c:\Users\####\Desktop\Python_Demo_Projects\Quiz_Program\assets\q1g.png" doesn't exist
from tkinter import *
from tkinter import filedialog
import os
import sys

temp_table = [("a","Answer is a because A","assets\q1g.png"),
              ("c","C is the answer","assets\q2g.png"),
              ("d","D is the answer","assets\q3g.png")]

current_placard = 0

def resource_path(relative_path):
    """ Get the absolute path to a resource, works for dev and for PyInstaller """
    try:
        # If running as a bundled exe, sys._MEIPASS will be the temp folder where the files are extracted
        base_path = sys._MEIPASS
    except AttributeError:
        # If running as a script, use the current directory
        base_path = os.path.dirname(os.path.abspath(__file__))
    
    return os.path.join(base_path, relative_path)

def load_quiz_file():
    global temp_table
    try:
        filepath = filedialog.askopenfilename(title="Open File",filetypes= (("text file","*.txt"),
                                            ("all files","*.*")))
        file = open(filepath,"r")
        temp_table = Variable(file.read())
        file.close()

        window.update_idletasks()
        #text_ans.insert("1.0","Quiz loaded Successfully")
           
    except Exception as e:
        print(f"Error reading from file: {e}")

def previous_slide():
    global current_placard
    if current_placard > 0:
        current_placard -= 1
    answer,explain,graphic = temp_table[current_placard]
    temp_graphic = Image(resource_path(graphic))
    label_q.config(image=temp_graphic)

window = Tk()

label_q = Label(window, height=23, background="red",text="Question placard will be displayed here.")
label_q.pack(fill=X,expand=True)

previous_slide()
window.mainloop()

文件位于正确的位置,甚至 Tkinter 显示回溯到正确的位置和文件,但它看不到它。我认为这就是我,但我一生都无法弄清楚为什么。

我尝试确认文件路径(正确),重新制作图像对象(没有变化), 打印图像路径(与不存在的状态相同)。

我过去也遇到过这个问题,但还没有到这种程度,就好像图像不存在一样。以前这只是一个简单的拼写错误,或者重新启动 VSC 即可修复。这次这些都不起作用。

python image tkinter
1个回答
0
投票

您需要的更改如下:

temp_table = [("a", "Answer is a because A", "assets\\q1g.png"),
              ("c", "C is the answer", "assets\\q2g.png"),
              ("d", "D is the answer", "assets\\q3g.png")]

显示图像所需的更改如下:

photo_image_object = None

def previous_slide():
    global current_placard
    global photo_image_object
    if current_placard > 0:
        current_placard -= 1
    answer, explain, graphic = temp_table[current_placard]

    path_to_image = resource_path(graphic)
    path_to_image = path_to_image.replace("\\", "\\\\")
    print(path_to_image)
    print(os.path.exists(path_to_image))
    photo_image_object = PhotoImage(file=path_to_image)
    label_r = Label(window, image=photo_image_object, height=200, width=700)
    label_r.pack()


window = Tk()

label_q = Label(window, height=2, background="red", text="Question placard will be displayed here.")
label_q.pack()

previous_slide()

window.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.