简体   繁体   中英

Why doesn't tkinter show me images?

Each time I try to load an image onto my tkinter app, it refuses to load, rather it springs different errors.

I have used so many different versions of the code. Below is the latest, which still dosen't work but throws an error.

from PIL import Image, ImageTk # I have added the import of ImageTk
import tkinter

window = tkinter.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
imageFile = '\User\PycharmProjects\BRIGHTBROWN\PyShop\tkinter\studentsRecord\myface.jpg'
im1 = ImageTk.PhotoImage(Image.open(imageFile))
panel = tkinter.Label(window, image = im1)
panel.pack(side = "bottom", fill = "both", expand = "yes")

window.mainloop()

The error thrown is:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \\UXXXXXXXX escape

The problem is with the path.
Make your you provide the complete path "C:\\...\\User\\..." . After that, there are several ways you can fix it:

Method #1:
Replace the backward slash with the forward one. For example: "C:/.../User/..."

Method #2:
Use r behind the string. For example: r"C:\\...\\User\\..."

Method #3:
Use Double Backward slashes. For example: "C:\\\\...\\\\User\\\\..."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM