Path for Tkinter Image script doubles forward slas

2019-08-04 11:32发布

I am working on a GUI to drive a robot wireless over a network. I am using pictures instead of label text for the arrows. I am correctly able to display a left arrow png graphic when I use this code:

from Tkinter import *
from PIL import Image, ImageTk

root = Tk()

leftImage = ImageTk.PhotoImage(Image.open("C:\Users\usr\Desktop\left.png"))


#rightImage = ImageTk.PhotoImage(Image.open("C:\Users\usr\Desktop\right.png"))

class GUI:

    def __init__(self, master):

        frame = Frame(master)
        frame.grid()


        left = Label(root, image = leftImage)
        left.grid(row=1, column=0)

        #right = Label(root, image = rightImage)
        #right.grid(row=1, column=2)


app = GUI(root)
root.mainloop()

Here is where it gets weird to me. When I remove the comments on the right arrow to try and include a left and right arrow, I get an error. The error is:

IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\Users\\usr\\Desktop\right.png'

I can't seem to figure out why it suddenly turns the "\" to a "\ \" for the path on the right arrow. Yet, it won't do draw an error on the path for the left arrow. I'm positive both files are on the right place. Any ideas on why the path of the rightImage is being interpreted differently than the left?

1条回答
劫难
2楼-- · 2019-08-04 12:09

You should use raw string literals for file paths on Windows (note r before the double quote):

leftImage = ImageTk.PhotoImage(Image.open(r"C:\Users\usr\Desktop\left.png"))
rightImage = ImageTk.PhotoImage(Image.open(r"C:\Users\usr\Desktop\right.png"))

It worked differently for the rightImage because \r is a special character (yes, it's one character, not two) - carriage return.

To quote a great man (and Python documentation):

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter "r" or "R"; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

查看更多
登录 后发表回答