0

I have an image (QR image) that i have to display it, and keep refreshing it every time. I tried many solutions but none worked, this is my code:

def QRDisplayer():
    global displayQR #I tried a tutorial wrote like this line, with it or without nothing changes 
    path = getcwd() + r"\temp\qr.png"
    try:
        displayQR.configure(image=PhotoImage(file=path))
    except: pass #I used try/except to avoid errors incase the image doesn't exists
    root.after(1000, QRDisplayer)


#main window:
root = Tk()
loadConfig()
root.title("")
root.resizable(False, False)
root.geometry("700x500")
displayQR = Label(root,image = None) #None bc it doesn't exists yet
displayQR.pack()
QRDisplayer()

if __name__ == "__main__":
    root.mainloop()

the image doesn't display at the first time, bc it's not exists, then I have to start refreshing the element until the photo shows up after reading. Also the photo is changeable so I have keep reading the file and displaying the content.

i spent 6h working on it, nothing worked including:

Python Tkinter Label redrawing every 10 seconds

Tkinter Reloading Window displaying an Image

Tkinter.Misc-class.html#update

Tkinter.Misc-class.html#update_idletasks

also I tried loops with Label["image"]=... ..., and threading lib.

Jawad
  • 186
  • 1
  • 14
  • The problem seems to be that you can't display an image because it doesn't exist yet. What are you hoping we can suggest? I can only imagine 2 possibilities... either display an alternative image saying *"Loading"* or wait till your image does exist. Or do the Microsoft thing and say *"Image loading in 4 seconds, 3 seconds, 2 seconds, 8 minutes, 8 minutes 1 second, 15 minutes..."* ;-) – Mark Setchell Jun 11 '21 at 07:41
  • @Mark Setchell as I mentioned before it does exists after while – Jawad Jun 11 '21 at 07:58

1 Answers1

1

You have to keep a reference to the PhotoImage instance first, which you are not:

def QRDisplayer():
    global img

    img  = None
    path = getcwd() + r"\temp\qr.png"
    try:
        img = PhotoImage(file=path)
    except TclError: # Error that gets invoked with invalid files
        img = None
    
    if img is not None:
        displayQR.configure(image=img)

    root.after(1000, QRDisplayer)

This feels like a better way to proceed so just incase if someother error occurs inside try you will be able to catch it, rather than ignoring all the errors with a plain except.

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46