image.png
"a simple text or file viewer component"
print('PP4E scrolledtext') from tkinter import *
class ScrolledText(Frame): def init(self, parent=None, text='', file=None): Frame.init(self, parent) self.pack(expand=YES, fill=BOTH) # make me expandable self.makewidgets() self.settext(text, file)
def makewidgets(self):
sbar = Scrollbar(self)
text = Text(self, relief=SUNKEN)
sbar.config(command=text.yview) # xlink sbar and text
text.config(yscrollcommand=sbar.set) # move one moves other
sbar.pack(side=RIGHT, fill=Y) # pack first=clip last
text.pack(side=LEFT, expand=YES, fill=BOTH) # text clipped first
self.text = text
def settext(self, text='', file=None):
if file:
text = open(file, 'r').read()
self.text.delete('1.0', END) # delete current text
self.text.insert('1.0', text) # add at line 1, col 0
self.text.mark_set(INSERT, '1.0') # set insert cursor
self.text.focus() # save user a click
def gettext(self): # returns a string
return self.text.get('1.0', END+'-1c') # first through last
if name == 'main': root = Tk() if len(sys.argv) > 1: st = ScrolledText(file=sys.argv[1]) # filename on cmdline else: st = ScrolledText(text='Words\ngo here') # or not: two lines def show(event): print(repr(st.gettext())) # show as raw string root.bind('<Key-Escape>', show) # esc = dump text root.mainloop()
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有