如何最好地从 tkinter canvas 转换坐标
How to best convert coordinates from tkinter canvas
我有一个简单的坐标系,我想在 tkinter 上显示 canvas。当用户点击一个单元格时,我想打印出它的位置:
canvas上每个单元格的高和宽都是15,所以当用户点击一个单元格时,对应的事件并不是实际的x和y坐标。
我的想法是在 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)
convert 函数看起来像这样:
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)
我想知道是否有更好的方法来做到这一点?对我来说看起来有点笨重并且有很多硬编码值。
使用div运算符//
converted_y = y // 15 + 1
converted_x_idx = x // 15
并将converted_x_idx映射到带有列表或str的字母ABCDE之一。
为了减少硬编码的内容:
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]
ycells 当然也一样。
我有一个简单的坐标系,我想在 tkinter 上显示 canvas。当用户点击一个单元格时,我想打印出它的位置:
canvas上每个单元格的高和宽都是15,所以当用户点击一个单元格时,对应的事件并不是实际的x和y坐标。
我的想法是在 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)
convert 函数看起来像这样:
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)
我想知道是否有更好的方法来做到这一点?对我来说看起来有点笨重并且有很多硬编码值。
使用div运算符//
converted_y = y // 15 + 1
converted_x_idx = x // 15
并将converted_x_idx映射到带有列表或str的字母ABCDE之一。
为了减少硬编码的内容:
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]
ycells 当然也一样。