【问题标题】:How to scroll a tkinter canvas to an absolute position?如何将 tkinter 画布滚动到绝对位置?
【发布时间】:2010-10-16 20:59:20
【问题描述】:

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

我想将画布滚动到我已经计算过的绝对位置(以像素为单位)。我该怎么做?

【问题讨论】:

    标签: python scroll tkinter-canvas


    【解决方案1】:

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

    self.canvas.xview_moveto(float(scroll_x+1)/img_width)
    self.canvas.yview_moveto(float(scroll_y+1)/img_height)
    
    • img_widthimg_height 是图像的尺寸。换句话说,它们是完整的可滚动区域。

    • scroll_xscroll_y 是所需左上角的坐标。

    • +1 是一个 magic 值,可以使其精确工作(但应仅在 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)
    

    【讨论】:

    • 使用 vertical_scrollbar.set(y0,y1) 应用滚动条中的更改。
    【解决方案2】:

    这是我已经做过的:

    # 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我必须添加,否则它会被取消一个)

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

    【讨论】:

      【解决方案3】:

      在 tkinter 中,您可以获得 PhotoImagefile 的 widthheight。使用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)
      

      【讨论】:

        猜你喜欢
        • 2017-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        • 2015-12-18
        • 1970-01-01
        • 1970-01-01
        • 2017-07-03
        相关资源
        最近更新 更多