问题
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 use PIL.
canvas.create_oval(val1, val2, val1+sz, val2+sz, fill=clr, outline=outln)
How would you get an image to fit inside a circle like so?
I would also certainly cull the edges around the image if you were wondering.
回答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 in range(200):
for x in range(200):
# using the formula for a circle:
# (x - h)^2 + (y - k)^2 = r^2
# any pixel outside our circle gets filled
if (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()
回答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.
来源:https://stackoverflow.com/questions/33072200/filling-a-tkinter-canvas-element-with-an-image