【问题标题】:How do I upload an image on Python using Tkinter?如何使用 Tkinter 在 Python 上上传图像?
【发布时间】:2017-07-24 20:29:37
【问题描述】:

我正在 Python 上使用 Tkinter 进行 GUI 编程。我正在使用网格管理器制作小部件。我创建了几个按钮,我想在它们上面上传一张图片。当我输入此代码时,它会给我一个escape sequence error

听说使用 PIL 不是个好主意?这是真的吗?

cookImage = PhotoImage(file = "image/C:\Users\terimaa\AppData\Local\Programs\Python\Python36-32\cook.gif")

【问题讨论】:

  • 请显示确切的错误。

标签: python user-interface tkinter widget


【解决方案1】:

Windows 文件名必须作为原始字符串输入:

cookImage = PhotoImage(file=r"C:\Users\terimaa\AppData\Local\Programs\Python\Python36-32\cook.gif")

这适用于所有 Python,而不仅仅是 PIL。

【讨论】:

  • 必须 是一个相当强的术语。您还可以使用正斜杠,或使用反斜杠转义的反斜杠。
  • @BryanOakley 很公平,但原始字符串是最干净的方式。我从不推荐正斜杠,因为它们只在大多数情况下起作用。
【解决方案2】:

用途:

path = r"a string with the path of the photo" 

注意r 前缀,它表示一个原始字符串。

...
img = ImageTk.PhotoImage(Image.open(file=path))
label = tk.Label(root, image = img)
label.something() #pack/grid/place
...

路径可以是:

  • 绝对 ("C:\Users\terimaa\AppData\Local\Programs\Python\Python36-32\cook.gif")

  • 相对("\cook.gif",取决于 Python 代码所在的位置)

【讨论】:

    【解决方案3】:

    如果您有一个正是您想要的image file,只需使用BitmapImagePhotoImage 打开它。请注意,Tcl/Tk 8.6,您应该在 Windows 上使用 3.6,也可以读取 .png 文件。在 Windows 上,在文件名前加上 'r' 或使用正斜杠:'C:/User/...'。

    实际的 PIL 包不再维护,仅适用于 2.x。那是新用户不应该使用的。兼容的继任者pillow(例如与python -m pip install pillow 一起安装)得到积极维护并与3.x 一起使用。兼容性扩展到导入语句:import PIL 导入枕头。 Pillows 允许人们操作图像并将多种格式转换为 tk 格式(ImageTk 类)。

    【讨论】:

      【解决方案4】:

      这是对移动图像最有帮助的确切代码

      from tkinter import *
      from tkinter import ttk
      from tkinter import filedialog
      import os, shutil
      
      class Root(Tk):
          def __init__(self):
              super(Root,self).__init__()
              self.title("thinter Dialog Widget")
              self.minsize(640,400)
      
              self.labelFrame = ttk.LabelFrame(self,text="Open A File")
              self.labelFrame.grid(column=0,row=1,padx= 20, pady= 20)
              self.btton()
      
          def btton(self):
              self.button = ttk.Button(self.labelFrame, text="Browse Afile", command=self.fileDailog)
              self.button.grid(column=1,row=1)
          def fileDailog(self):
              self.fileName = filedialog.askopenfilename(initialdir = "/", title="Select A File",filetype=(("jpeg","*.jpg"),("png","*.png")))
              self.label = ttk.Label(self.labelFrame, text="")
              self.label.grid(column =1,row = 2)
              self.label.configure(text = self.fileName)
              os.chdir('e:\\')
              os.system('mkdir BACKUP')
              shutil.move(self.fileName,'e:\\')
      
      
      
      if __name__ == '__main__':
          root = Root()
          root.mainloop()
      

      由于权限被拒绝,您无法将图像移动到 c 盘:此代码在 python 3.8、3,7 上成功运行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-28
        • 2010-12-03
        • 1970-01-01
        • 2014-10-02
        相关资源
        最近更新 更多