Minimal scrolling canvas

CL wanted a scrolling canvas model to which he could refer others. Mightily distressed that the first eight instances he came across in books and on the Web all were complicated or do things end-users consistently call "stupid" (scrollbars don't really behave properly, and so on)--or both!-- he offers this example as an alternative:


    set height 400
    set width  600
    set borderwidth 2

    set hscroll .hscroll
    set vscroll .vscroll
    set canvas .c

    scrollbar $hscroll -orient horiz -command "$canvas xview"
    scrollbar $vscroll               -command "$canvas yview"
    canvas $canvas -relief sunken -borderwidth $borderwidth \
                              -width $width -height $height \
                              -xscrollcommand "$hscroll set" \
                              -yscrollcommand "$vscroll set"
        # Ensure that window resizings retain scroll bars.
    pack $hscroll -side bottom -fill x
    pack $vscroll -side right  -fill y
    pack $canvas  -side right  -fill both  -expand 1
  # Somebody want to express the above in "grid"?
  # That'd be good practice.

        # Put something visible on the canvas 
        # so we have a sense of what we're seeing.
    $canvas create line 0 0       $width $height
    $canvas create line 0 $height $width 0
    $canvas configure -scrollregion [$canvas bbox all]

It will be interesting to see when its first fault emerges.


ulis, 2003-07-05: If you need grid in place of pack:

        # Ensure that window resizings retain scroll bars.
    grid $canvas  -row 0 -column 0 -sticky nswe
    grid $vscroll -row 0 -column 1 -sticky ns
    grid $hscroll -row 1 -column 0 -sticky ew
    grid rowconfig . 0 -weight 1
    grid columnconfig . 0 -weight 1

Important! The usage of this scrolling canvas is that one creates [L1 ] widgets onto the canvas, rather than managing them as children. In particular, if you're trying to

    frame $canvas.subframe ...

rather than

    $canvas add rectangle ...

you're headed for trouble.

MG Aug 21 2007 - Does anyone have a minimal example of a scrollable canvas meant for containing other widgets? I'm trying to put a frame inside a canvas to scroll it, but my lack of canvas-use in the past is coming back to haunt me, and I can't find any good, small examples of how to do it...

MG, a few minutes later Discovered what the problem I was having was, oddly enough on the canvas page - my widgets weren't children of the canvas, and so stuck out over it. Making all the widgets displayed on the canvas children of it solved the problem (thanks DKF!).