如何将 tkinter 画布滚动到绝对位置?
我正在使用 Python 和 tkinter。我有一个 Canvas
小部件,它将仅显示一张图像。大多数情况下,图像会大于画布尺寸,但有时会更小。我们只关注第一种情况(图像比画布大)。
我想将画布滚动到我已经计算过的绝对位置(以像素为单位)。我怎样才能做到这一点?
I'm using Python and tkinter. I have a Canvas
widget that will display just one image. Most times the image will be larger than the canvas dimensions, but sometimes it will be smaller. Let's just focus on the first case (image larger than canvas).
I want to scroll the canvas to an absolute position that I have already calculated (in pixels). How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
经过大约半个小时的尝试,我得到了另一个似乎更好的解决方案:
img_width
和img_height
是图像的尺寸。换句话说,它们是完整的可滚动区域。scroll_x
和scroll_y
是所需左上角的坐标。+1
是一个使其精确工作的神奇值(但仅当scroll_x/y
为非负数时才应应用)请注意,不需要当前小部件尺寸,只需内容的尺寸。
即使图像小于小部件尺寸(因此
scroll_x/y
可能为负),此解决方案也能很好地工作。编辑:改进版本:
After trying for around half hour, I got another solution that seems better:
img_width
andimg_height
are the dimensions of the image. In other words, they are the full scrollable area.scroll_x
andscroll_y
are the coordinates of the desired top-left corner.+1
is a magic value to make it work precisely (but should be applied only ifscroll_x/y
is non-negative)Note that the current widget dimension is not needed, only the dimension of the contents.
This solution works very well even if the image is smaller than the widget size (and thus the
scroll_x/y
can be negative).EDIT: improved version:
这就是我已经做过的:
但是......正如你所看到的......它非常hackish和丑陋。对于本应简单的事情来说,有太多的解决方法。 (加上我需要添加的神奇
+1
,否则它将相差一)还有其他人有另一个更好、更干净的解决方案吗?
This is what I have already done:
But... As you can see... it's very hackish and ugly. To much workaround for something that should be simple. (plus that magic
+1
I was required to add, or it would be off-by-one)Does anyone else have another better and cleaner solution?
在 tkinter 中,您可以获得
PhotoImage
文件的width
和height
。您可以在使用canvas.create_image时调用它In tkinter you can get the
width
andheight
of aPhotoImage
file. You can just call it when you usecanvas.create_image
我通过使用 self.canvas.scan_dragto(x, y) 找到了这个解决方案
编辑:我开发了一个可以滚动、缩放和旋转图像的界面。让我们从我的界面中提取代码。
当我想保存图像的当前位置时,我使用以下命令:
I found this solution by using
self.canvas.scan_dragto(x, y)
Edit: I develop an interface which can scroll, zoom, and rotate an image. Let's extract from my interface the code.
When I want to save the current position of image I use this: