Drawing a png image on a tkinter canvas python

白昼怎懂夜的黑 提交于 2021-02-09 10:58:13

问题


I am trying to create a simple game using tkinter in python 3.5 using the canvas widget. For this game I am need to be able to use a transparent (png) image. Here is my code:

from PIL import ImageTk
from tkinter import Tk, Canvas

root = Tk()
im = ImageTk.PhotoImage(file="test.png")
canvas = Canvas(root, width=900, height=900)
canvas.pack()
canvasImage = canvas.create_image(0, 0, image=im, anchor="nw")
root.mainloop()

The problem is that, despite getting no errors i can't load an image with a transparent background but i can load png images with no transparent background.


回答1:


You should try this:

from tkinter import * 
root = Tk()
canvas = Canvas(root, width=500, height=500)
canvas.pack()
img = PhotoImage(file='path/your_image.png')
canvas.create_image(250, 250, image=img)
root.mainloop()

Output here



来源:https://stackoverflow.com/questions/46388292/drawing-a-png-image-on-a-tkinter-canvas-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!