scrollable_frame.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. ## Source: http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
  2. from tkinter import *
  3. class VerticalScrolledFrame(Frame):
  4. """A pure Tkinter scrollable frame that actually works!
  5. * Use the 'interior' attribute to place widgets inside the scrollable frame
  6. * Construct and pack/place/grid normally
  7. * This frame only allows vertical scrolling
  8. """
  9. def __init__(self, parent, *args, **kw):
  10. Frame.__init__(self, parent, *args, **kw)
  11. # create a canvas object and a vertical scrollbar for scrolling it
  12. vscrollbar = Scrollbar(self, orient=VERTICAL)
  13. vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
  14. canvas = Canvas(self, bd=0, highlightthickness=0,
  15. yscrollcommand=vscrollbar.set)
  16. canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
  17. vscrollbar.config(command=canvas.yview)
  18. # reset the view
  19. canvas.xview_moveto(0)
  20. canvas.yview_moveto(0)
  21. # create a frame inside the canvas which will be scrolled with it
  22. self.interior = interior = Frame(canvas)
  23. interior_id = canvas.create_window(0, 0, window=interior,
  24. anchor=NW)
  25. # track changes to the canvas and frame width and sync them,
  26. # also updating the scrollbar
  27. def _configure_interior(event):
  28. # update the scrollbars to match the size of the inner frame
  29. size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
  30. canvas.config(scrollregion="0 0 %s %s" % size)
  31. if interior.winfo_reqwidth() != canvas.winfo_width():
  32. # update the canvas's width to fit the inner frame
  33. canvas.config(width=interior.winfo_reqwidth())
  34. #NOTE my own addition
  35. canvas.yview_moveto(1)
  36. interior.bind('<Configure>', _configure_interior)
  37. def _configure_canvas(event):
  38. if interior.winfo_reqwidth() != canvas.winfo_width():
  39. # update the inner frame's width to fill the canvas
  40. canvas.itemconfigure(interior_id, width=canvas.winfo_width())
  41. canvas.bind('<Configure>', _configure_canvas)
  42. return