如何将 Tkinter 画布坐标转换为窗口? [英] How to convert Tkinter canvas coordinate to window?

查看:37
本文介绍了如何将 Tkinter 画布坐标转换为窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Tkinter 中将画布坐标转换为窗口坐标?

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)

推荐答案

使用 canvasxcanvasy 方法,给定一个零参数,来计算 x/y可见画布的左上角.然后只需使用数学将画布坐标转换为相对于窗口的东西.

Use the canvasx and canvasy 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.

# upper left corner of the visible region
x0 = self.canvas.canvasx(0)
y0 = self.canvas.canvasy(0)

# given a canvas coordinate cx/cy, convert it to window coordinates:
wx0 = cx-x0
wy0 = cy-y0

例如,如果画布一直滚动到顶部和左侧,则 x0 和 y0 将为零.您提供的任何画布坐标都将与窗口坐标相同(即:0,0 的画布 x/y 将对应于窗口坐标 0,0).

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).

如果您向下和向右滚动 100 像素,则画布坐标 100,100 将转换为窗口坐标 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.

这为您提供了一个相对于画布左上角的值.如果你需要这个相对于整个窗口的左上角,使用 winfo_xwinfo_y 来获取画布相对于窗口的坐标并做更多的数学运算.或者,使用 winfo_rootxwinfo_rooty 获取小部件相对于屏幕的坐标.

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 and winfo_y to get the coordinate of the canvas relative to the window and do a little more math. Or, use winfo_rootx and winfo_rooty to get the coordinates of the widget relative to the screen.

这篇关于如何将 Tkinter 画布坐标转换为窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆