# # Tkinter 3000 # # this demo implements a simple text list widget, and shows # how to make it scrollable # from WCK import Widget, ScrollMixin, TextMixin, FONT, FOREGROUND import string class ScrollableText(ScrollMixin, TextMixin, Widget): ui_option_height = 24 ui_option_width = 80 ui_option_yscrollcommand = None # enables vertical scrolling def __init__(self, master, **options): self.data = [] self.top = 0 self.visible = 0 self.ui_init(master, options) # # ScrollMixin interface def ui_scroll_yinfo(self): # return total, top, bottom return len(self.data), self.top, self.top + self.visible - 1 def ui_scroll_yset(self, top, units=0, pages=0): # change top offset top = top + units + pages * self.visible total = len(self.data) top = max(0, min(top, total - self.visible + 1)) if top != self.top: self.ui_damage() self.top = top self.ui_scroll_update() def ui_handle_resize(self, width, height): self.visible = int(height / self.ui_draw.textsize(None, self.font)[1]) self.ui_scroll_yset(self.top) # update scrollbar def ui_handle_repair(self, draw, x0, y0, x1, y1): width, height = draw.textsize(None, self.font) y = 0 for i in range(self.top, len(self.data)): if y >= y1: break draw.text((0, y), string.rstrip(str(self.data[i])), self.font) y = y + height # # public api def getdata(self): return self.data def setdata(self, data, top=None): if top is None: top = self.top self.data = data self.ui_scroll_yset(top) self.ui_damage() # redraw me if __name__ == "__main__": import Tkinter root = Tkinter.Tk() root.title("demoScrolledText") scrollbar = Tkinter.Scrollbar(root) scrollbar.pack(side="right", fill="y") widget = ScrollableText(root, font="courier 8", background="white", yscrollcommand=scrollbar.set) widget.pack(fill="both", expand=1) scrollbar.config(command=widget.yview) import sys widget.setdata(open(sys.argv[0]).readlines()) root.mainloop()