tkiner组件之滚动文本框(scrolledtext )相关操作

1.创建一个滚动文本框

import  tkinter as tk
from tkinter import scrolledtext  
root = tk.Tk()
root.title('text')
root.geometry('100x100')
scr = scrolledtext.ScrolledText(root,width=10,height=5)
scr.pack()
root.mainloop()

如图
tkiner组件之滚动文本框(scrolledtext )相关操作_第1张图片
2.读取text文件内容显示到滚动文本框

import  tkinter as tk
from tkinter import scrolledtext
root = tk.Tk()
root.title('text')
root.geometry('300x100')
scr = scrolledtext.ScrolledText(root,width=50,height=5)
scr.pack()
with open('test') as f:
    for line in f:
        scr.insert('end',line)#末尾插入
        #scr.insert('insert',line)#光标插入

root.mainloop()

如图:
tkiner组件之滚动文本框(scrolledtext )相关操作_第2张图片
3.文本内容的删除

import  tkinter as tk
from tkinter import scrolledtext
root = tk.Tk()
root.title('text')
root.geometry('300x100')
scr = scrolledtext.ScrolledText(root,width=50,height=5)
scr.pack()
for i in range(10):
    scr.insert('end', i)
    scr.insert('end', '\n')
scr.delete(1.0) #删除第一个元素
scr.delete(1.0,'end') #删除所有元素
root.mainloop()

4.文本内容的获取

import  tkinter as tk
from tkinter import scrolledtext
root = tk.Tk()
root.title('text')
root.geometry('300x100')
scr = scrolledtext.ScrolledText(root,width=50,height=5)
scr.pack()
for i in range(10):
    scr.insert('end', i)
    scr.insert('end', '\n')  #

print(scr.get(1.0,'end')) #获取文本中所有内容
print(scr.get(1.0)) #获取文本中第一行的内容
root.mainloop()

5.打印选中的文本内容

import  tkinter as tk
from tkinter import scrolledtext
root = tk.Tk()
root.title('text')
root.geometry('300x100')
scr = scrolledtext.ScrolledText(root,width=50,height=5)
scr.pack()
for i in range(10):
    scr.insert('end', i)
    scr.insert('end', '\n')  #
def showselection():
     try:
         s = scr.selection_get()
    except Exception as e:
         print('....')
    else:
         print(s)
tk.Button(root,text='sava',command=showselection).pack()
root.mainloop()

如图:
tkiner组件之滚动文本框(scrolledtext )相关操作_第3张图片

你可能感兴趣的:(tkiner,tkinter)