Skip to content Skip to sidebar Skip to footer

Filling A Tkinter Canvas Element With An Image

Is there any way to fill a Tkinter element (more specifically an oval) with an image. If not, is there any way to resize an image to fit into an oval? I also would prefer not to

Solution 1:

In plain Tkinter your options are limited. One thing you could do is create a 'mask' image that has a transparent circle in the middle. Then lower your own image in behind it. (not very efficient though)

from tkinter import *

root = Tk()
canvas = Canvas(root, width=200, height=200, bd=0,
                highlightthickness=0)
canvas.pack()

mask = PhotoImage(width=200, height=200)
cx,cy = 100,100# image & circle center point
r = 100# circle radius
r_squared = r*r
for y inrange(200):
    for x inrange(200):
        # using the formula for a circle:# (x - h)^2 + (y - k)^2 = r^2# any pixel outside our circle gets filledif (x - cx)**2 + (y - cy)**2 > r_squared:
            mask.put('blue', (x,y))

canvas.create_image(100,100, image=mask, anchor='c')

myimage = PhotoImage(file='bigpython.gif')
item = canvas.create_image(100,100, image=myimage, anchor='c')
canvas.lower(item)

root.mainloop()

Solution 2:

No, there is no way to put an image inside an oval. That is to say, you can't make one fill up an oval. Images can only be rectangular.

Your only choice for resizing images without using PIL is to resize it by factors of two.

Solution 3:

I've tried all ways to try and get a photo to fit inside a circle but the only kind-of effective way is to resize the image using the Paint 2D app in Windows and then using the resized image as the image used to fill the circle.

Post a Comment for "Filling A Tkinter Canvas Element With An Image"