Tkinter Image脚本的路径使斜杠加倍 [英] Path for Tkinter Image script doubles forward slash

查看:85
本文介绍了Tkinter Image脚本的路径使斜杠加倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GUI来通过网络驱动机器人无线.我使用的是图片而不是箭头的标签文本.使用此代码时,我可以正确显示左箭头png图形:

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'

我似乎无法弄清楚为什么突然将右箭头的路径中的"\"变成"\\".但是,它不会在向左箭头的路径上绘制错误.我很肯定两个文件都放在正确的位置.关于为何对rightImage的路径的解释与对左图像的解释有所不同的任何想法吗?

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?

推荐答案

对于Windows上的文件路径,应使用原始字符串文字(请在双引号前注意r):

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"))

它对于rightImage的工作方式有所不同,因为\r是一个特殊字符(是,它是一个字符,而不是两个)-

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

引用一位伟人(和Python文档):

To quote a great man (and Python documentation):

反斜杠(\)字符用于转义那些 否则有特殊含义,例如换行符,反斜杠本身, 或引号字符.字符串文字可以有选择地加上前缀 带有字母"r"或"R";这样的字符串称为原始字符串,并使用 解释反斜杠转义序列的不同规则.

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.

这篇关于Tkinter Image脚本的路径使斜杠加倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆