【问题标题】:PIL ImageTk equivalent in Python 3.xPython 3.x 中的 PIL ImageTk 等效项
【发布时间】:2012-06-19 14:20:55
【问题描述】:

我正在使用 Tkinter 开发一个应用程序,该应用程序使用 png 图像文件的数据库作为图标。为了在应用程序中使用所述图像,我使用 PIL 的 Image.open 打开它们,通过 ImageTk.PhotoImage 函数运行它,然后将其传递给小部件构造函数。

问题是,我正在尝试将整个项目移植到 Python 3.x,由于 PIL 不支持 Python 3,我不知道如何将图标加载到应用程序中。

如果有人知道一种解决方案,可以让我使用这些图标而不必将它们全部转换为.gif 位图,我将非常感激!

【问题讨论】:

    标签: python png tkinter python-imaging-library


    【解决方案1】:

    该示例在画布上显示图像。

    from PIL import Image, ImageTk
    # From the PIL (Python Imaging Library) module, we import the Image and ImageTk modules.
    
    
    self.img = Image.open("tatras.jpg")
    self.tatras = ImageTk.PhotoImage(self.img)
    
    
    # Tkinter does not support JPG images internally. As a workaround, we
    # use the Image and ImageTk modules.
    
    canvas = Canvas(self, width=self.img.size[0]+20,  height=self.img.size[1]+20)
    
    # We create the Canvas widget. It takes the size of the image into account. It is 20px wider and 20px higher than the actual image size.
    
    canvas.create_image(10, 10, anchor=NW, image=self.tatras)
    

    【讨论】:

      【解决方案2】:

      您可以在 Python 3.3 或更早版本中使用 Pillow 处理 png 图像。

      取自here:

      Pillow >= 2.0.0 支持 Python 版本:2.6、2.7、3.2、3.3。枕头

      【讨论】:

        【解决方案3】:

        PNG 文件,即使具有透明度,也能在 Linux 上的 python 3.4.1 中正确显示在 tkinter 和 ttk 中,即使只有 GIF 和 PPM/PGM 支持是 documented。

        上面的PNG图像包含透明度。

        from tkinter import *          
        
        root = Tk()                    
        
        photo = PhotoImage(file="example.png")
        photo_label = Label(image=photo)
        photo_label.grid()             
        photo_label.image = photo      
        
        text = Label(text="Text") # included to show background color
        text.grid()    
        
        root.mainloop()
        

        上面的代码正确地渲染了具有透明度的图像,如下所示:

        请注意,屏幕截图是在没有窗口装饰和深色 GUI 配色方案的设置上制作的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-09
          • 1970-01-01
          • 2019-08-13
          相关资源
          最近更新 更多