Skip to content Skip to sidebar Skip to footer

Correct Way To Set Scrollbar Position In Python Tkinter

I am making a basic text editor and I am saving the scroll position in a file on closing the program. Then when opening the program it will read the scroll position from the file a

Solution 1:

You can't expect the saved yview to work in all cases. If the file has been edited, the proportions could be all wrong.

The tuple you get from yview represents the fraction visible at the top and the fraction visible at the bottom. You can call yview_moveto to set the position at the top, and then let tkinter take care of the fraction at the bottom.

For example, if the yview you've saved is (0.42, 0.75), then you just need to call yview_moveto('0.42'). This will cause the view to be adjusted so that the given offset is at the top of the window.

Solution 2:

In case of widgets update with change bbox sizes, i use a followed snippet to keep scroll position:

#before repaint store vsb position caclulated in pixels from top
bbox = canvas.bbox(ALL)
self.mem_vsb_pos = canvas.yview()[0] * (bbox[3] - bbox[1])

#after repaint (back calculation):
bbox = canvas.bbox(ALL)
canvas.yview_moveto(self.do_vsb_pos / (bbox[3]-bbox[1]))

#before repaint - if need repaint from topself.mem_vsb_pos = 0.0

Post a Comment for "Correct Way To Set Scrollbar Position In Python Tkinter"