简体   繁体   中英

Address error: (unicode error) 'unicodeescape' codec can't decode

Code to show image is giving a syntax error when I use the Address to the image.

from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

Scare = Tk()
Scare.title('?????')
Countdown = 2
CountTotal = 2
CountTotal = IntVar()

def CountdownWork():
    global Countdown
    if Countdown > 0:
        Countdown = Countdown -1
        CountTotal.set(Countdown)
        Scare.after(1000, CountdownWork)
    else:
        ImageAddress = 'C:\Users\KINSLED\Desktop\New folder\ScareTest.jpg'
        ImageItself = Image.open(ImageAddress)
        ImageNumpyFormat = np.asarray(ImageItself)
        plt.imshow(ImageNumpyFormat)
        plt.draw()
        plt.pause(5) # pause how many seconds
        plt.close()



Count = Label(Scare, font=('arial', 10, 'bold'), textvariable=CountTotal, 
bd=30, bg='SeaGreen1', justify='right').grid(row=7,columnspan=8)

CountdownWork()

Scare.mainloop()

The Syntax Error is highlighting the space just after the equals in ImageAdress.

The Error is:

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated\\UXXXXXXXX escape

In Python strings, the backslash "\\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\\t" is a tab, "\\n" is a newline, and "\\r" is a carriage return.

I believe the error is referencing your adress, specifically the special character "\\" in it. You cannot use "\\" in your string as it will escape the string. You could try using "\\\\" in your address, I think this should work.

Please see here for futher reading on the subject: http://www.pitt.edu/~naraehan/python2/tutorial7.html

The error lies in the way you've typed the file path. Windows uses backslashes \\ to separate files and directories in filenames, but any time the interpreter sees these special characters, it looks for an unicode escape sequnce, like \\n . To insert a backslash you need to insert \\\\ , one slash to trigger the escape sequence and another to indicate the backslash itlesf as the desired special character.

Your assignment then becomes

ImageAddress = 'C\\:Users\\KINSLED\\Desktop\\New folder\\ScareTest.jpg'

which does't throw any error on my simulation.

而不是在python中使用\\ use /这种方式你可以克服这个“(Unicode错误)'unicodeescape'编解码器无法解码位置2-3的字节:截断\\ UXXXXXXXX转义”错误

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