blob: 749a06a6f00fd2a7df658e3dd1d9fcca15ba8a51 [file] [log] [blame]
Martin v. Löwise354d782008-12-29 16:03:04 +00001"""A ScrolledText widget feels like a text widget but also has a
2vertical scroll bar on its right. (Later, options may be added to
3add a horizontal bar as well, to make the bars disappear
4automatically when not needed, to move them to the other side of the
5window, etc.)
Guido van Rossum18468821994-06-20 07:49:28 +00006
Martin v. Löwise354d782008-12-29 16:03:04 +00007Configuration options are passed to the Text widget.
8A Frame widget is inserted between the master and the text, to hold
9the Scrollbar widget.
10Most methods calls are inherited from the Text widget; Pack, Grid and
11Place methods are redirected to the Frame widget however.
12"""
13
14__all__ = ['ScrolledText']
15
16from tkinter import Frame, Text, Scrollbar, Pack, Grid, Place
17from tkinter.constants import RIGHT, LEFT, Y, BOTH
Guido van Rossum18468821994-06-20 07:49:28 +000018
Serhiy Storchakadc0d5712018-10-12 19:01:00 +030019
Guido van Rossum460b6bb1994-07-06 21:54:39 +000020class ScrolledText(Text):
Martin v. Löwise354d782008-12-29 16:03:04 +000021 def __init__(self, master=None, **kw):
22 self.frame = Frame(master)
23 self.vbar = Scrollbar(self.frame)
Fred Draked038ca82000-10-23 18:31:14 +000024 self.vbar.pack(side=RIGHT, fill=Y)
Martin v. Löwise354d782008-12-29 16:03:04 +000025
26 kw.update({'yscrollcommand': self.vbar.set})
27 Text.__init__(self, self.frame, **kw)
28 self.pack(side=LEFT, fill=BOTH, expand=True)
Fred Draked038ca82000-10-23 18:31:14 +000029 self.vbar['command'] = self.yview
Guido van Rossum460b6bb1994-07-06 21:54:39 +000030
Guilherme Polobcd03df2009-08-18 15:35:57 +000031 # Copy geometry methods of self.frame without overriding Text
32 # methods -- hack!
33 text_meths = vars(Text).keys()
Georg Brandl780d5e02010-12-28 10:56:20 +000034 methods = vars(Pack).keys() | vars(Grid).keys() | vars(Place).keys()
35 methods = methods.difference(text_meths)
Guido van Rossum61d36372001-12-10 16:42:43 +000036
37 for m in methods:
Fred Draked038ca82000-10-23 18:31:14 +000038 if m[0] != '_' and m != 'config' and m != 'configure':
39 setattr(self, m, getattr(self.frame, m))
Martin v. Löwise354d782008-12-29 16:03:04 +000040
41 def __str__(self):
42 return str(self.frame)
43
44
45def example():
Martin v. Löwise354d782008-12-29 16:03:04 +000046 from tkinter.constants import END
47
48 stext = ScrolledText(bg='white', height=10)
Georg Brandl780d5e02010-12-28 10:56:20 +000049 stext.insert(END, __doc__)
Martin v. Löwise354d782008-12-29 16:03:04 +000050 stext.pack(fill=BOTH, side=LEFT, expand=True)
51 stext.focus_set()
52 stext.mainloop()
53
Serhiy Storchakadc0d5712018-10-12 19:01:00 +030054
Martin v. Löwise354d782008-12-29 16:03:04 +000055if __name__ == "__main__":
56 example()