python - 从python 3中的pygame表面在tkinter中加载图像

标签 python image tkinter pygame geometry-surface

我想从 pygame surface 在 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

最佳答案

PhotoImage class只能读取 GIFPGM/PPM 文件,直接从文件或作为 base64 编码字符串。


你应该使用 Python Imaging Library用于为 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()

enter image description here

关于python - 从python 3中的pygame表面在tkinter中加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13463529/

相关文章:

python - 如何休眠到特定时间 YYYY-MM-DD HH :MM:SS?

python - Raspberry Pi python显示内存中的图像

html - 在灵活的 div 中垂直和水平居中图像

python - 类型错误 : leftClick() missing 1 required positional argument: 'password'

python - 如何在 tkinter Entry 小部件中插入临时文本?

Python Tkinter canvas.xview 单位

python - Django 保存方法静默失败

python - 使用 Django-datatable-view 不显示数据表

python - 如何从 DataFrame TimeIndex 中提取频率

javascript - 上传 PHP 时图像到达服务器时为 0 字节