如何将 Tkinter 画布坐标转换为窗口坐标?
有没有办法在 Tkinter 中将画布坐标转换为窗口坐标?
这与从窗口坐标转换为画布坐标相反,其操作如下:
x = canvas.canvasx(event.x)
Is there a way to convert canvas coordinates to window coordinates in Tkinter?
It would be the opposite of converting from window to canvas coordinate, which is done like this:
x = canvas.canvasx(event.x)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
canvasx
和canvasy
方法(参数为零)来计算可见画布左上角的 x/y。然后只需使用数学将画布坐标转换为相对于窗口的坐标即可。例如,如果画布一直滚动到顶部和左侧,则 x0 和 y0 将为零。您给出的任何画布坐标都将与窗口坐标相同(即:0,0 的画布 x/y 将对应于窗口坐标 0,0)。
如果您向下向右滚动 100 个像素,则画布坐标 100,100 将转换为窗口坐标 0,0,因为该像素位于窗口的左上角。
这将为您提供相对于画布左上角的值。如果您需要相对于整个窗口的左上角,请使用
winfo_x
和winfo_y
获取画布相对于窗口的坐标并进行更多数学运算。或者,使用winfo_rootx
和winfo_rooty
获取小部件相对于屏幕的坐标。Use the
canvasx
andcanvasy
methods, giving an argument of zero, to compute the x/y of the upper left corner of the visible canvas. Then just use math to convert the canvas coordinate to something relative to the window.For example, if the canvas is scrolled all the way to the top and left, x0 and y0 will be zero. Any canvas coordinate you give will be the same as the window coordinate (ie: canvas x/y of 0,0 will correspond to window coordinate 0,0).
If you've scrolled 100 pixels down and to the right, a canvas coordinate of 100,100 will translate to a window coordinate of 0,0 since that is the pixel that is in the upper left corner of the window.
This gives you a value relative to the upper left corner of the canvas. If you need this relative to the upper left corner of the whole window, use
winfo_x
andwinfo_y
to get the coordinate of the canvas relative to the window and do a little more math. Or, usewinfo_rootx
andwinfo_rooty
to get the coordinates of the widget relative to the screen.