0

I'm trying to write a simple script to display an image in a window using tkinter.

I've tried to use PIL/Pillow and I've tried using the standard tkinter features but always get the same error when the script tries to read the filepath.

  File "c:/Users/Sandip Dhillon/Desktop/stuff/dev_tests/imgtest2.py", line 6
    photo=tk.PhotoImage(file="C:\Users\Sandip Dhillon\Pictures\DESlogo1.png")
                             ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Here is my code,

import tkinter as tk

window=tk.TK()
window.geometery("400x300+200+100")

photo=tk.PhotoImage(file="C:\Users\Sandip Dhillon\Pictures\DESlogo1.png")

l1=tk.Label(text="image")
l1.pack()
l2=tk.Label(image=photo)
l2.pack

window.mainloop()

Thank you!

1 Answers1

1

Backslashes are escape characters in Python strings, so your string is interpreted in an interesting way.

Either:

  • use forward slashes: tk.PhotoImage(file="C:/Users/Sandip Dhillon/Pictures/DESlogo1.png")
  • use a raw string: tk.PhotoImage(file=r"C:\Users\Sandip Dhillon\Pictures\DESlogo1.png")

    Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters.

  • double the slashes: tk.PhotoImage(file="C:\\Users\\Sandip Dhillon\\Pictures\\DESlogo1.png")

    Escape sequence: \\: Backslash (\)

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Btw I don't know why but python converts `"\Sandip"` to `\\Sandip"` so the only time you need to escape the backslash is when you have `"\U..."`. So `file="C:\\Users\Sandip Dhillon\Pictures\DESlogo1.png"` should also work. I think it is because `"\u..."` is used to start a Unicode escape sequence. – TheLizzard May 18 '21 at 15:26
  • Yes, it should work, but it's better to escape everything instead of having to remember that `'"abfnrtvxNuU` are parts of escape sequences :) – AKX May 18 '21 at 15:30
  • What does the `o` stand for? Python converts `"\o"` to `"\\o"` (automatically escapes the backslash). – TheLizzard May 18 '21 at 15:32
  • @TheLizzard Oops, I meant `"\123"` (octal sequences). – AKX May 18 '21 at 15:35
  • Thanks guys that helped a bunch, it's working now. Appreciate it, @TheLizzard you've come to my rescue once again haha – Sandip Dhillon May 18 '21 at 15:38
  • @SandipDhillon I didn't do much but consider accepting the answer if it was what you were looking for. Click [here](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) to learn how to accept an answer. – TheLizzard May 18 '21 at 15:41