我正在使用Python和tkinter。我有一个Canvas
只显示一个图像的小部件。大多数时候图像会大于画布尺寸,但有时会更小。让我们只关注第一种情况(图像大于画布)。
我想将画布滚动到我已经计算过的绝对位置(以像素为单位)。我怎样才能做到这一点?
我正在使用Python和tkinter。我有一个Canvas
只显示一个图像的小部件。大多数时候图像会大于画布尺寸,但有时会更小。让我们只关注第一种情况(图像大于画布)。
我想将画布滚动到我已经计算过的绝对位置(以像素为单位)。我怎样才能做到这一点?
尝试了大约半小时后,我得到了另一个似乎更好的解决方案:
self.canvas.xview_moveto(float(scroll_x+1)/img_width)
self.canvas.yview_moveto(float(scroll_y+1)/img_height)
img_width
img_height
是图像的尺寸。换句话说,它们是完整的可滚动区域。
scroll_x
并且scroll_y
是所需左上角的坐标。
+1
是使其精确工作的神奇值(但应仅在scroll_x/y
非负数时应用)
请注意,不需要当前小部件尺寸,只需要内容的尺寸。
scroll_x/y
即使图像小于小部件大小(因此可能为负),此解决方案也能很好地工作。
编辑:改进版:
offset_x = +1 if scroll_x >= 0 else 0
offset_y = +1 if scroll_y >= 0 else 0
self.canvas.xview_moveto(float(scroll_x + offset_x)/new_width)
self.canvas.yview_moveto(float(scroll_y + offset_y)/new_height)
这是我已经做过的:
# Little hack to scroll by 1-pixel increments.
oldincx = self.canvas["xscrollincrement"]
oldincy = self.canvas["yscrollincrement"]
self.canvas["xscrollincrement"] = 1
self.canvas["yscrollincrement"] = 1
self.canvas.xview_moveto(0.0)
self.canvas.yview_moveto(0.0)
self.canvas.xview_scroll(int(scroll_x)+1, UNITS)
self.canvas.yview_scroll(int(scroll_y)+1, UNITS)
self.canvas["xscrollincrement"] = oldincx
self.canvas["yscrollincrement"] = oldincy
但是......正如你所看到的......它非常丑陋和丑陋。对于应该很简单的事情有很多解决方法。(加上我需要添加的魔法+1
,否则它会一个接一个)
还有其他人有其他更好更清洁的解决方案吗?
在 tkinter 中,您可以获得文件的width
and height
。PhotoImage
您可以在使用时调用它canvas.create_image
imgrender = PhotoImage(file="something.png")
##Other canvas and scrollbar codes here...
canvas.create_image((imgrender.width()/2),(imgrender.height()/2), image=imgrender)
## The top left corner coordinates is (width/2 , height/2)