2

我正在使用Pythontkinter。我有一个Canvas只显示一个图像的小部件。大多数时候图像会大于画布尺寸,但有时会更小。让我们只关注第一种情况(图像大于画布)。

我想将画布滚动到我已经计算过的绝对位置(以像素为单位)。我怎样才能做到这一点?

4

3 回答 3

5

尝试了大约半小时后,我得到了另一个似乎更好的解决方案:

self.canvas.xview_moveto(float(scroll_x+1)/img_width)
self.canvas.yview_moveto(float(scroll_y+1)/img_height)
  • img_widthimg_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)
于 2010-10-16T21:38:14.040 回答
0

这是我已经做过的:

# 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,否则它会一个接一个)

还有其他人有其他更好更清洁的解决方案吗?

于 2010-10-16T21:00:00.997 回答
0

在 tkinter 中,您可以获得文件的widthand heightPhotoImage您可以在使用时调用它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)
于 2019-12-26T00:37:51.430 回答