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