在Python3中从pygame表面加载tkinter中的图像
我想从pygame界面加载tkinter中的图像,我遇到了一个问题 这就是我目前正在尝试的:在Python3中从pygame表面加载tkinter中的图像,python,image,tkinter,pygame,geometry-surface,Python,Image,Tkinter,Pygame,Geometry Surface,我想从pygame界面加载tkinter中的图像,我遇到了一个问题 这就是我目前正在尝试的: image= pygame.image.tostring(surf, 'RGB') tkimage= tkinter.PhotoImage(data= image) canvas.create_image(0, 0, tkimage) 但不幸的是,我得到了这个错误: _tkinter.TclError: couldn't recognize image data 只能直接从文件或作为base64编码
image= pygame.image.tostring(surf, 'RGB')
tkimage= tkinter.PhotoImage(data= image)
canvas.create_image(0, 0, tkimage)
但不幸的是,我得到了这个错误:
_tkinter.TclError: couldn't recognize image data
只能直接从文件或作为base64
编码字符串读取GIF
和PGM
/PPM
文件
您应该使用来加载和创建Tk的映像 下面是一个例子:
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()
----更新------
你能解释一下为什么这会帮助用户解决手头的问题吗?
import pygame
from pygame.locals import *
from PIL import Image
import ImageTk
import Tkinter
# load image in pygame
pygame.init()
surf = pygame.image.load('pic_temp.png') # you can use any Surface a Camers is also an Surface
mode = "RGB"
# export as string / import to PIL
image_str = pygame.image.tostring(surf, mode) # use 'RGB' to export
size = (640, 480)
#image = Image.fromstring(mode, size, image_str)
# use frombuffer() - fromstring() is no longer supported
image = Image.frombuffer(mode, size, image_str, 'raw', mode, 0, 1) # use 'RGB' to import
# create Tk window/widgets
root = Tkinter.Tk()
tkimage = ImageTk.PhotoImage(image) # use ImageTk.PhotoImage class instead
label = Tkinter.Label(root, image=tkimage)
label.pack()
root.mainloop()