ScrolledText.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """A ScrolledText widget feels like a text widget but also has a
  2. vertical scroll bar on its right. (Later, options may be added to
  3. add a horizontal bar as well, to make the bars disappear
  4. automatically when not needed, to move them to the other side of the
  5. window, etc.)
  6. Configuration options are passed to the Text widget.
  7. A Frame widget is inserted between the master and the text, to hold
  8. the Scrollbar widget.
  9. Most methods calls are inherited from the Text widget; Pack, Grid and
  10. Place methods are redirected to the Frame widget however.
  11. """
  12. __all__ = ['ScrolledText']
  13. from Tkinter import Frame, Text, Scrollbar, Pack, Grid, Place
  14. from Tkconstants import RIGHT, LEFT, Y, BOTH
  15. class ScrolledText(Text):
  16. def __init__(self, master=None, **kw):
  17. self.frame = Frame(master)
  18. self.vbar = Scrollbar(self.frame)
  19. self.vbar.pack(side=RIGHT, fill=Y)
  20. kw.update({'yscrollcommand': self.vbar.set})
  21. Text.__init__(self, self.frame, **kw)
  22. self.pack(side=LEFT, fill=BOTH, expand=True)
  23. self.vbar['command'] = self.yview
  24. # Copy geometry methods of self.frame without overriding Text
  25. # methods -- hack!
  26. text_meths = vars(Text).keys()
  27. methods = vars(Pack).keys() + vars(Grid).keys() + vars(Place).keys()
  28. methods = set(methods).difference(text_meths)
  29. for m in methods:
  30. if m[0] != '_' and m != 'config' and m != 'configure':
  31. setattr(self, m, getattr(self.frame, m))
  32. def __str__(self):
  33. return str(self.frame)
  34. def example():
  35. import __main__
  36. from Tkconstants import END
  37. stext = ScrolledText(bg='white', height=10)
  38. stext.insert(END, __main__.__doc__)
  39. stext.pack(fill=BOTH, side=LEFT, expand=True)
  40. stext.focus_set()
  41. stext.mainloop()
  42. if __name__ == "__main__":
  43. example()