Reputation: 33
Once again I am stucked.
In a canvas I display 9 images Every 8 rows I add a column. This is only for testing purposes. At the end the images should be hundreds. I am trying to identify each image with a unique number. In order to do this I have an event which gives me the coordinates of the canvas. And here comes the noobs part. To get this unique number my code is
if x_on_grid==0 and y_on_grid==448:
index_bin=0
elif x_on_grid==0 and y_on_grid==384:
index_bin=1
elif x_on_grid==0 and y_on_grid==320:
index_bin=2
elif x_on_grid==0 and y_on_grid==256:
index_bin=3
elif x_on_grid==0 and y_on_grid==192:
index_bin=4
elif x_on_grid==0 and y_on_grid==128:
index_bin=5
elif x_on_grid==0 and y_on_grid==64:
index_bin=6
elif x_on_grid==0 and y_on_grid==0:
index_bin=7
elif x_on_grid==64 and y_on_grid==448: #new column
index_bin=8
elif x_on_grid==64 and y_on_grid==384:
index_bin=9
Of course it works perfectly, but it's not scientific at all. I am trying to reduce all these lines with a loop but I can't get the number needed, only the last one.
Any ideas?
Best
Upvotes: 0
Views: 43
Reputation: 7006
Consider the following code
import tkinter as tk
def onclick(event):
print(vars(event))
nearest = event.widget.find_closest(event.x,event.y)
nearest_tag = event.widget.gettags(nearest)[0]
print(nearest_tag)
def drawCircles(c):
size = 20
for i in range(100):
row = i % 10
col = i // 10
x1 = (row * size) + 30
y1 = (col * size) + 30
c.create_oval((x1,y1,x1+size,y1+size),tags="image_%03d" % i)
root = tk.Tk()
c = tk.Canvas(root,width=400,height=400,bg="white")
c.grid()
c.bind("<Button-1>",onclick)
drawCircles(c)
root.mainloop()
I'm using circles(ovals) rather than images but the principle is still the same. I draw 100 circles and as I draw then I assign a tag to them in the format image_?
. When I click on the canvas, the find_closest
method is used to determine which of the circles is nearest to the click. It then looks up the tag (or tags) of that object and prints it out.
No need for long winded if-elif-else statements.
Upvotes: 1