text是一个强大的组件,可插入文字,图片,组件等元素。在做小项目的时候要用到他,边学习边实践边写笔记。
1.定义一个text
from tkinter import * #生成主窗体 root=Tk() root.title('Text组件测试') #设置窗体大小 root.geometry("400x300") text=Text(root,width=40,height=20) text.pack() root.mainloop()
#text 的 width 和 height 的单位不是像素,而是一个字的宽和高,所以 width=20,height=20 并不是一个正方形
2.设置滚动条
from tkinter import * #生成主窗体 root=Tk() root.title('Text组件测试') #设置滚动条 scroll=Scrollbar() #设置text的大小 text=Text(root,width=40,height=20) #将滚动条填充,放在右边,y是竖直方向 text.pack(side=LEFT,fill=Y) scroll.pack(side=RIGHT,fill=Y) #将滚动条和文本框关联 scroll.config(command=text.yview) text.config(yscrollcommand=scroll.set) root.mainloop()
3.插入文本
from tkinter import * #生成主窗体 root=Tk() root.title('Text组件测试') #设置滚动条 scroll=Scrollbar() #设置text的大小 text=Text(root,width=40,height=20) #将滚动条填充,放在右边,y是竖直方向 text.pack(side=LEFT,fill=Y) scroll.pack(side=RIGHT,fill=Y) #将滚动条和文本框关联 scroll.config(command=text.yview) text.config(yscrollcommand=scroll.set) #插入文本 texts='1234567890abcdefg' text.insert(1.0,texts) root.mainloop()
#如果要使文本框不能被编辑的话,设置state=DISABLE 就行了。如果要改回可编辑,设置state=NORMAL
text.config(state=NORMAL) text.insert(END,'我是插入内容') text.config(state=DISABLED)
4.获取一个输入内容插入
from tkinter import * #生成主窗体 root=Tk() root.title('Text组件测试') #设置滚动条 scroll=Scrollbar() #设置text的大小 text=Text(root,width=40,height=20) #将滚动条填充,放在右边,y是竖直方向 text.pack(side=LEFT,fill=Y) scroll.pack(side=RIGHT,fill=Y) #将滚动条和文本框关联 scroll.config(command=text.yview) text.config(yscrollcommand=scroll.set) #插入文本 texts='1234567890abcdefg' text.insert(1.0,texts) def insert_text(): text.config(state='normal') value=var.get() text.insert(END,value) text.config(state='disable') var.set("") var=StringVar() var.set("") entry=Entry(root,width=10,textvariable=var) entry.place(x=10,y=150) btn=Button(root,text='插入',command=insert_text) btn.place(x=100,y=150) root.mainloop()