I have a simple coordinate system that I want to display on a tkinter canvas. When the user clicks on a cell, I want to print out its location:
Each cell on the canvas has a height and width of 15, so when the user clicks on a cell, the corresponding event is not the actual x and y coordinate.
What I had in mind is drawing rectangles with the different heights and widths on the canvas:
x1 = 0
x2 = 0
y1 = 15
y2 = 15
for i in range(4):
for i in range(8):
canvas.create_rectangle(x1, x2, y1, y2, fill="blue",tags="playbutton", outline="green")
x1 = 15
y1 = 15
x1 = 0
y1 = 15
x2 = 15
y2 = 15
def clicked(*args):
x = args[0].x
y = args[0].y
print(convert_to_coordinates(x,y)
canvas.tag_bind("playbutton","<Button-1>",clicked)
The convert function would then look something like this:
def convert_to_coord(x,y):
converted_x = None
converted_y = None
if x >= 0 and x <= 15:
converted_x = "A"
elif x > 15 and x <= 30:
converted_x = "B"
elif x > 30 and x <= 45:
converted_x = "C"
elif x > 45 and x <= 60:
converted_x = "D"
elif x > 60 and x <= 75:
converted_x = "E"
if y >= 0 and y <=15:
converted_y = "1"
elif y > 15 and y <= 30:
converted_y = "2"
elif y > 30 and y <= 45:
converted_y = "3"
elif y > 45 and y <= 60:
converted_y = "4"
return "{}{}".format(converted_x, converted_y)
I was wondering if there is a better way to do this? Looks kinda clunky and lots of hardcoded values to me.
CodePudding user response:
Use div operator //
converted_y = y // 15 1
converted_x_idx = x // 15
And map converted_x_idx to one of the letters ABCDE with a list or str.
CodePudding user response:
For the sake of less hardcoded stuff:
dx = 15 # this can be an optional argument of the convert function
xcells = ['A', 'B', 'C', 'D', 'E']
for jx, xcell in enumerate(xcells):
if x > jx*dx and x <= (jx 1)*dx:
converted_x = xcell
break
if x == 0:
converted_x = xcells[0]
same for ycells of course.