简体   繁体   English

使用PIL或枕头绘制图像并用TKinter显示

[英]Using PIL or pillow to draw an image and display it with TKinter

I want to draw an image programmatically. 我想以编程方式绘制图像。 Essentially I am talking about setting each single pixel as a map of the image, and I would like to do that using PIL/pillow. 本质上,我是在谈论将每个像素设置为图像映射,我想使用PIL /枕头来实现。 Then, I would like to display it on the screen. 然后,我想在屏幕上显示它。 The GUI is based on TKinter. GUI基于TKinter。

root = Tk()
root.wm_title("Lands - A world generator")
root.resizable(0,0)

prepare_menu()

canvas = Canvas(root, width=canvas_width, height=canvas_height)
canvas.pack()

root.mainloop()

The prepare_menu sets the menu and associates one entry with an event handler, which calls the function show_elevation_map like this: prepare_menu设置菜单并将一个条目与事件处理程序相关联,该事件处理程序将如下调用函数show_elevation_map

def show_elevation_map(p, width, height):    
    hm = platec.get_heightmap(p)
    img = PIL.Image.new('RGBA', (width, height))
    pixels = img.load()
    for y in range(0, height):
        for x in range(0, width):            
            pixels[x, y] = (255, 0, 0, 255)
    pi = ImageTk.PhotoImage(img)
    sprite = canvas.create_image(100, 100, image=pi)
    canvas.update()

I tried it like this, but I cannot see anything on the screen, while I would expect to see everything red. 我这样尝试过,但是我看不到屏幕上的任何东西,而我希望看到的一切都是红色的。 What am I doing wrong here? 我在这里做错了什么?

Thanks. 谢谢。

Your image is likely getting garbage collected. 您的图片可能会被垃圾回收。 You need to save a persistent reference to the image. 您需要保存对图像的持久引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM