Reputation: 983
I'm creating a simple CAD application in tkinter using the canvas. Hollow cylinder is created by using two oval objects as shown in the sample code below. The inner circle/oval has the same fill as the background of the canvas, thereby creating an illusion of a hollow object.
If I plot the cylinder over another object with a different fill (as shown with the rectangle), the hollow effect is lost.
It is impossible to know the color of every object that will be created on the canvas, or a user might create a cylinder at one point and move it to a different location/over a different object with a different fill color.
How do I create hollow object in these cases?
Sample Code:
import Tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=350, background="RoyalBlue4")
canvas.pack()
#Plot on the canvas
def cylinder(OD, ID):
canvas.create_oval(OD, outline="black", fill="SkyBlue1")
canvas.create_oval(ID, outline="black", fill="RoyalBlue4")
def rectangle(dim):
canvas.create_rectangle(dim, outline="black", fill="white")
rectangle([10, 10, 250, 150])
cylinder([75, 30, 175, 130], [85, 40, 165, 120])
cylinder([150, 200, 250, 300], [175, 225, 225, 275])
root.mainloop()
Upvotes: 0
Views: 1641
Reputation: 19174
You need to get the color of at lest the pixel under the center of the cylinder. In the absence of a get_pixel_color method, I came up with this extension of your cylinder function.
def cylinder(OD, ID):
x, y = (ID[0]+ID[2])/2, (ID[1]+ID[3])/2
under = canvas.find_overlapping(x, y, x, y)
fillcolor = canvas.itemcget(under[0], 'fill') if under else "RoyalBlue4"
print('x, y, under, color = ', x, y, under, fillcolor)
canvas.create_oval(OD, outline="black", fill="SkyBlue1")
canvas.create_oval(ID, outline="black", fill=fillcolor)
The canvas background color should be named and the name used here and in the canvas create statement. The print is needed for development.
If there would ever be multiple items under the cylinder, you will have to experiment to see whether the top is the first (as assumed above) or last (in which case, use -1 instead of 0). (Lets hope the order is not random.) If a cylinder were to partially overlap, you would need either a transparent color (not available, at least from tkinter) or something much more elaborate.
Upvotes: 1