pythonimagetkinterpygamegeometry-surface

Load image in tkinter from pygame surface in python 3


I would like to load an image in tkinter from a pygame surface and I am having a problem.

This is what I am currently trying:

image= pygame.image.tostring(surf, 'RGB')
tkimage= tkinter.PhotoImage(data= image)
canvas.create_image(0, 0, tkimage)

but I unfortunately get this error:

_tkinter.TclError: couldn't recognize image data

Solution

  • The PhotoImage class can only read GIF and PGM/PPM files, either directly from a file or as base64 encoded string.


    You should use the Python Imaging Library for loading and creating the image for Tk.

    Here's an example:

    import pygame
    from PIL import Image
    import ImageTk
    import Tkinter
    
    # load image in pygame
    pygame.init()
    surf = pygame.image.load('bridge.png')
    
    # export as string / import to PIL
    image_str = pygame.image.tostring(surf, 'RGB')         # use 'RGB' to export
    w, h      = surf.get_rect()[2:]
    image     = Image.fromstring('RGB', (w, h), image_str) # use 'RGB' to import
    
    # create Tk window/widgets
    root         = Tkinter.Tk()
    tkimage      = ImageTk.PhotoImage(image) # use ImageTk.PhotoImage class instead
    canvas       = Tkinter.Canvas(root)
    
    canvas.create_image(0, 0, image=tkimage)
    canvas.pack()
    root.mainloop()
    

    enter image description here