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 для исправления. На этот раз ничего из этого не помогло.
[code]Traceback (most recent call last): File "c:\Users\####\Desktop\Python_Demo_Projects\Quiz_Program\problematic.py", line 51, in 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 [/code] [code]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__))
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() [/code] Файл находится в правильном месте, и даже Tkinter показывает обратную трассировку, идущую в нужное место и файл, но он его не видит. Я предполагаю, что это я, но я не могу понять, почему. Я пробовал подтвердить путь к файлу (правильный), переделать объект изображения (без изменений). , печать пути к изображению (так же, как и отсутствие состояний). У меня была эта проблема в прошлом, но не в такой степени, как будто изображение не не существует. Раньше это была простая опечатка или перезапуск VSC для исправления. На этот раз ничего из этого не помогло.