美文网首页
十七、文字区域Text

十七、文字区域Text

作者: 蝉时雨丶 | 来源:发表于2020-07-07 18:29 被阅读0次

文字区域Text的基本概念

Text的构造方法如下。
Text(父对象,options,···)

Text()方法的第一个参数是父对象,表示这个文字区域将建立在哪一个父对象内。
下列是Text()方法内其他常用的options参数。
(1)gb或background:背景色彩。
(2)borderwidth或bd:边界宽度,默认是2像素。
(3)cursor:当鼠标光标在复选框上时的光标形状。
(4)exportselection:如果执行选择操作时,所选择的字符串会自动输出至剪贴板,
如果想要避免如此可以设置exportselection=0。
(5)bg或foreground:字形色彩。
(6)font:字形。
(7)height:高,单位是字符高,实际高度会视字符高度而定。
(8)highlightbackground:当文本框取得焦点时的背景颜色。
(9)highlightcolor当文本框取得焦点时的颜色。
(10)highlightthickness:取得焦点时的厚度,默认是1。
(11)insertbackground:插入光标的颜色,默认是黑色。
(12)insertborderwidth:围绕插入游标的3D厚度,默认是0.
(13)padx:Text 左/右框与文字最左/最右的间距。
(14)pady:Text上/下框与文字最上/最下的间距。
(15)relief:默认是relief=SUNKEN,可由此控制文字外框。
(16)selectbackground:被选取字符串的背景色彩。
(17)selectborderwidth:选取字符串时的边界厚度,默认值是1。
(18)selectforeground:被选取字符串的前景色彩。
(19)state:输入状态,默认是NORMAL,表示可以输入,DISABLED则是无法编辑。
(20)tab:可设置按Tab键时,如何定位插入点。
(21)width:Text的宽,单位是字符串。
(22)wrap:可控制某行文字太长时的处理,默认是wrap=CHAR,当某行文字太长时,
可从字符做断行;当wrap=WORD时,只能从字做断行。
(23)xscrollommand:在x轴使用滚动条。
(24)yscrollommand:在y轴使用滚动条。

样例:建立一个高度是2,宽度是30的Text文字区域。

from tkinter import *

root=Tk()
root.title("ch17_1")

text=Text(root,height=2,width=30)
text.pack()

root.mainloop()
image.png

可以发现,若是输入文字超过两行,将导致第一行数据被隐藏,若是输入更多行将造成更多
文字被隐藏,虽然可以用移动光标的方式重新看到第一行文字,但是对于不了解程序结构而言的
人而言,还是比较容易误会Text区域的内容。
当然,也可以重新设置Text()方法内的height和width参数,让Text文字区域可以容纳更多数据。

插入文字insert()

insert()可以将字符串插入指定的索引位置,它的使用格式如下。
insert(index,string)
若是参数index位置使用END或是INSERT,表示将字符串插入文件末端位置。

样例:将字符串插入Text文字区域末端位置。

from tkinter import *

root=Tk()
root.title("ch17_2")

text=Text(root,height=3,width=30)
text.pack()

text.insert(END,"Python王者归来\nJava王者归来\n")
text.insert(INSERT,"深石数字公司")

root.mainloop()
image.png

Text加上滚动条Scrollbar设计

样例:将Scrollbar应用在Text控件中,让整个Text文字区域增加y轴的滚动条。

from tkinter import *

root=Tk()
root.title("ch17_4")

yscrollbar=Scrollbar(root)
text=Text(root,height=5,width=30)
yscrollbar.pack(side=RIGHT,fill=Y)
text.pack()
yscrollbar.config(command=text.yview)
text.config(yscrollcommand=yscrollbar.set)

str="""略"""
text.insert(END,str)

root.mainloop()
image.png

样例2,增加x轴的滚动条。

from tkinter import *

root=Tk()
root.title("ch17_5")

xscrollbar=Scrollbar(root,orient=HORIZONTAL)
yscrollbar=Scrollbar(root)
text=Text(root,height=5,width=30,wrap="none")
xscrollbar.pack(side=BOTTOM,fill=X)
yscrollbar.pack(side=RIGHT,fill=Y)
text.pack()
xscrollbar.config(command=text.xview)
yscrollbar.config(command=text.yview)
text.config(xscrollcommand=xscrollbar.set)
text.config(yscrollcommand=yscrollbar.set)

str="""略"""
text.insert(END,str)

root.mainloop()
image.png

上述程序可以拖动水平滚动条左右移动,查看完整的内容。如果我们将窗口变大,仍然可以
看到所设置的Text文字区域,由于我们没有使用fill或expand参数做更进一步的设置,所以
Text文字区域将保持height和width的参数设置,不会更改。

设置Text文字区域时,如果想让此区域随着窗口更改大小,在使用pack()时,可适度地使用
fill和expand参数。

样例3:让Text文字区域随着窗口扩充而扩充。为了让文字区域明显,将此区域地背景设为黄色。
text=Text(root,height=5,width=30,wrap="none",bg="lightyellow")
xscrollbar.pack(side=BOTTOM,fill=X)
yscrollbar.pack(side=RIGHT,fill=Y)
text.pack(fill=BOTH,expand=True)

字形

family

family用于设置Txt文字区域地字形,下面将以实例说明此参数对于文字区域字形的影响。

样例:建立一个Text文字区域,然后在上方建立一个OptionMenu的对象,在这个对象内建立
了Arial、Times、Courier三种字形,其中,Arial是默认的字形,用户可以在Text文字区域输入
文字,然后选择字形,可以看到所输入的文字将因所选择的字形而有不同的变化。

from tkinter import *
from tkinter.font import Font
def familyChanged(event):
    f=Font(family=familyVar.get())
    text.configure(font=f)

root=Tk()
root.title("ch17_7")

familyVar=StringVar()
familyFamily=("Arial","Times","Courier")
familyVar.set(familyFamily[0])
family=OptionMenu(root,familyVar,*familyFamily,command=familyChanged)
family.pack(pady=2)

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.focus_set()

root.mainloop()
image.png

讲解:f=Font(family=familyVar.get())可以取得所有选择的font family,然后text.configure(font=f)
设置让Text文字区域使用此字形。

使用tkinter.ttk的OptionMenu会有不同的效果。

weight

weight用于设置Text文字区域的字是否粗体,下面将以实例说明此参数对于文字区域
字形的影响。

样例:先使用Frame建立一个Toolbar,然后将family对象放在此Toolbar内,同时靠左
对齐,然后建立weight对象,默认的weight是normal,将此对象放在family对象右边
,用户可以在Text文字区域输入文字,然后可以选择字形或是weight方式,可以看到所输入
的文字将因所选择的字形或weight方式而有不同的变化。

from tkinter import *
from tkinter.font import Font
def familyChanged(event):
    f=Font(family=familyVar.get())
    text.configure(font=f)

def weightChanged(event):
    f=Font(weight=weightVar.get())
    text.configure(font=f)

root=Tk()
root.title("ch17_8")
root.geometry("300x180")

toolbar=Frame(root,relief=RAISED,borderwidth=1)
toolbar.pack(side=TOP,fill=X,padx=2,pady=1)

familyVar=StringVar()
familyFamily=("Arial","Times","Courier")
familyVar.set(familyFamily[0])
family=OptionMenu(toolbar,familyVar,*familyFamily,command=familyChanged)
family.pack(side=LEFT,pady=2)

weightVar=StringVar()
weightFamily=("normal","bold")
weightVar.set(weightFamily[0])
weight=OptionMenu(toolbar,weightVar,*weightFamily,command=weightChanged)
weight.pack(pady=3,side=LEFT)

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.focus_set()

root.mainloop()
image.png

上述程序实例所使用的OptionMenu是使用tkinter的Widget,如果使用tkinter.ttk将看到不一样
的外观。

size

size用于设置Text文字区域的字号,下面将以实例说明此参数对于文字区域字号的影响。

样例:Ccombobox对象设置字号,字号的区间是8~30,其中默认大小是12。将此对象放
在weight对象右边,用于可以在Text文字区域输入文字,然后可以选择字形、weight或
字号,可以看到所输入的文字将因所选择的字形或weight或字号而有不同的变化。

from tkinter import *
from tkinter.font import Font
from tkinter.ttk import *

def familyChanged(event):
    f=Font(family=familyVar.get())
    text.configure(font=f)

def weightChanged(event):
    f=Font(weight=weightVar.get())
    text.configure(font=f)
def sizeSelected(event):
    f=Font(size=sizeVar.get())
    text.configure(font=f)

root=Tk()
root.title("ch17_9")
root.geometry("300x180")

toolbar=Frame(root,relief=RAISED,borderwidth=1)
toolbar.pack(side=TOP,fill=X,padx=2,pady=1)

familyVar=StringVar()
familyFamily=("Arial","Times","Courier")
familyVar.set(familyFamily[0])
family=OptionMenu(toolbar,familyVar,*familyFamily,command=familyChanged)
family.pack(side=LEFT,pady=2)

weightVar=StringVar()
weightFamily=("normal","bold")
weightVar.set(weightFamily[0])
weight=OptionMenu(toolbar,weightVar,*weightFamily,command=weightChanged)
weight.pack(pady=3,side=LEFT)

sizeVar=IntVar()
size=Combobox(toolbar,textvariable=sizeVar)
sizeFamily=[x for x in range(8,30)]
size["value"]=sizeFamily
size.current(4)
size.bind("<<ComboboxSelected>>",sizeSelected)
size.pack(side=LEFT)

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.focus_set()

root.mainloop()
image.png

选取文字

Text对象的get()方法可以取得目前所选的文字,在使用Text文字区域时,如果有选取文字
操作发生时,Text对象会将所选文字的起始索引放在SEL_FIRST,结束索引放在SEF_LAST,
将SEL_FIRST和SEL_LAST当作get()的参数,就可以获得目前所选的文字。

样例:当单击Print selection按钮时,可以在Python Shell窗口列出目前所选的文字。

from tkinter import *

def selectedText():
    try:
        selText=text.get(SEL_FIRST,SEL_LAST)
        print("选取文字:",selText)
    except TclError:
        print("没有选取文字")

root=Tk()
root.title("ch17_10")
root.geometry("300x180")

btn=Button(root,text="Print selection",command=selectedText)
btn.pack(pady=3)

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Love You Lkie A Love Song")

root.mainloop()
image.png

选取文字

Text对象的get()方法可以取得目前所选的文字,在使用Text文字区域时,如果有选取文字
操作发生时,Text对象会将所选文字的起始索引放在SEL_FIRST,结束索引放在SEF_LAST,
将SEL_FIRST和SEL_LAST当作get()的参数,就可以获得目前所选的文字。

样例:当单击Print selection按钮时,可以在Python Shell窗口列出目前所选的文字。

from tkinter import *

def selectedText():
    try:
        selText=text.get(SEL_FIRST,SEL_LAST)
        print("选取文字:",selText)
    except TclError:
        print("没有选取文字")

root=Tk()
root.title("ch17_10")
root.geometry("300x180")

btn=Button(root,text="Print selection",command=selectedText)
btn.pack(pady=3)

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Love You Lkie A Love Song")

root.mainloop()

认识Text的索引

Text对象的索引并不是单一数字,而是一个字符串。索引的目的是让Text控件处理更进一步的
文件操作。下列是常见的索引形式。

(1)line/column("line.column"):计数方式line是从1开始,column从0开始计数,中间用句点
分隔。
(2)INSERT:目前插入点的位置。
(3)CURRENT:光标目前位置相对于字符的位置。
(4)END:缓冲区最后一个字符后的位置。
(5)表达式Expression:索引使用表达式,下列是说明。
1."+count chars",count是数字,例如,"+2c"索引往后移动两个字符。
2."-count chars",count是数字,例如,"-2c"索引往前移动两个字符。

上述是用字符串形式表示,也可以使用index()方法,实际用字符串方式列出索引内容。

样例:将所选的文字以常用的line.column字符串方式显示。

from tkinter import *

def selectedText():
    try:
        selText=text.get(SEL_FIRST,SEL_LAST)
        print("选取文字:",selText)
        print("selectiionstart:",text.index(SEL_FIRST))
        print("selectionend:",text.index(SEL_LAST))
    except TclError:
        print("没有选取文字")

root=Tk()
root.title("ch17_10")
root.geometry("300x180")

btn=Button(root,text="Print selection",command=selectedText)
btn.pack(pady=3)

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Love You Lkie A Love Song")

root.mainloop()
image.png

样例2,列出INSERT、CURRENT、END的位置。

from tkinter import *

def printIndex():
    print("INSERT :",text.index(INSERT))
    print("CURRENT:",text.index(CURRENT))
    print("END:",text.index(END))

root=Tk()
root.title("ch17_12")
root.geometry("300x180")

btn=Button(root,text="Print index",command=printIndex)
btn.pack(pady=3)

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Love You Lkie A Love Song\n")
text.insert(END,"梦醒时分")

root.mainloop()
image.png

由于鼠标光标一直在Print index按钮上,所以列出的CURRENT是在1.0索引位置,其实
如果我们在文件位置单击时,CURRENT的索引位置会变动,此时INSERT的索引位置会
随着CURRENT更改。之前我们了解使用insert()方法,可以在文件末端插入文字,当我们
了解索引的概念后,其实也可以利用索引位置插入文件。

样例3:在指定索引位置插入文字。

from tkinter import *

root=Tk()
root.title("ch17_13")
root.geometry("300x180")

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Love You Lkie A Love Song\n")
text.insert(1.14,"梦醒时分")

root.mainloop()
image.png

建立书签

在编辑文件时,可以在文件特殊位置建立书签(Marks),方便查询。书签是无法显示的,但会在
编辑系统内部被记录。如果书签内容被删除,则此书签也将自动被删除。其实在tkinter内默认
有两个书签:INSERT和CURRENT。下列是常用的书签相关方法。
(1)index(mark):传回指定书签的line和column。
(2)mark_names():传回这个Text对象所有的书签。
(3)mark_set(mark,index):在指定的index位置设置书签。
(4)mark_unset(mark):取消指定书签设置。

样例:设置两个书签,然后列出书签间的内容。

from tkinter import *

root=Tk()
root.title("ch17_14")
root.geometry("300x180")

text=Text(root)

for i in range(1,10):
    text.insert(END,str(i)+' Python GUI设计王者归来 \n')

text.mark_set("mark1","5.0")
text.mark_set("mark2","8.0")

print(text.get("mark1","mark2"))
text.pack(fill=BOTH,expand=True)

root.mainloop()
image.png

标签

标签(Tags)是指一个区域文字,然后我们可以为这个区域取一个名字,这个名字称作标签,
可以使用此标签名字代表这个区域文字。有了标签后,我们可以针对此标签左更进一步的工作,
例如,将字形、色彩等应用在此标签上。下列是常用的标签方法。

(1)tag_add(tagname,startindex[,endindex]···):将startindex和endindex间的文字名称为
tagname书签。
(2)tag_config(tagname,options,···):可以为标签执行特定的编辑,或动作绑定。
1.background:背景颜色。
2.borderwidth:文字外围厚度,默认是0。
3.font:字形。
4.foreground:前景颜色。
5.justfy:对齐方式,默认是LEFT,也可以是RIGHT或CENTER。
6.overstrike:如果是True,加上删除线。
7.underline:如果是True,加上下划线。
8.wrap:当使用wrap模式时,可以使用NONE、CHAR、或WORD。
(3)tag_delete(tagname):删除此标签,同时移除此标签特殊的编辑或绑定。
(4)tag_remove(tagment[,startindex[,endindex]]···):删除标签,但是不移除此标签特殊的
编辑或绑定。

除了可以使用tag_add()自行定义标签外,系统还有一个内建标签SEL,代表所选取的区间。

样例:先设定两个书签,然后将两个书签间的文字设为tag1,最后针对此tag1设置前景颜色
是蓝色,背景颜色是浅黄色。

from tkinter import *

root=Tk()
root.title("ch17_15")
root.geometry("300x180")

text=Text(root)

for i in range(1,10):
    text.insert(END,str(i)+' Python GUI设计王者归来 \n')

text.mark_set("mark1","5.0")
text.mark_set("mark2","8.0")

text.tag_add("tag1","mark1","mark2")
text.tag_config("tag1",foreground="blue",background="lightyellow")
text.pack(fill=BOTH,expand=True)

root.mainloop()
image.png

样例2:设计当选取文字时,可以将依所选的文字大小显示所选文字。

from tkinter import *
from tkinter.font import Font
from tkinter.ttk import *

def sizeSelected(event):
    f=Font(size=sizeVar.get())
    text.tag_config(SEL,font=f)

root=Tk()
root.title("ch17_15")
root.geometry("300x180")

toolbar=Frame(root,relief=RAISED,borderwidth=1)
toolbar.pack(side=TOP,fill=X,padx=2,pady=1)

sizeVar=IntVar()
size=Combobox(toolbar,textvariable=sizeVar)
sizeFamily=[x for x in range(8,30)]
size["value"]=sizeFamily
size.current(4)
size.bind("<<ComboboxSelected>>",sizeSelected)
size.pack()

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Five Hunder Miles\n")
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")
text.focus_set()

root.mainloop()
image.png

上诉程序在设计时我们是使用SEL当作变更字号的依据,所以当我们取消选取时,原先编辑的
文字又将比返回原先大小。在程序设计时我们也可以在insert()方法的第三个参数增加标签tag,
之后则可以直接设置此标签。

from tkinter import *
from tkinter.font import Font
from tkinter.ttk import *

def sizeSelected(event):
    f=Font(size=sizeVar.get())
    text.tag_config(SEL,font=f)

root=Tk()
root.title("ch17_15")
root.geometry("300x180")

toolbar=Frame(root,relief=RAISED,borderwidth=1)
toolbar.pack(side=TOP,fill=X,padx=2,pady=1)

sizeVar=IntVar()
size=Combobox(toolbar,textvariable=sizeVar)
sizeFamily=[x for x in range(8,30)]
size["value"]=sizeFamily
size.current(4)
size.bind("<<ComboboxSelected>>",sizeSelected)
size.pack()

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Five Hunder Miles\n","a")
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")
text.focus_set()

text.tag_config("a",foreground="blue",justify=CENTER,underline=True)

root.mainloop()
image.png

Cut/Copy/Paste功能

编辑文件时剪切/复制/粘贴是很常用的功能,这些功能其实被内建在tkinter中了。如果我们想
要删除所编辑的文件可以用delete()方法,在这个方法中如果想要删除的是一个字符,可以使用
一个参数,这个参数可以是索引,下面是一个实例。
delete(INSERT) #删除插入点字符

如果想要删除所选的文本块,可以使用两个参数:起始索引与结束索引。
delete(SEL_FIRST,SEL_LAST) #删除所选文本块
delete(startindex,endindex) #删除指定区间文本块

在编辑程序时常常会需要删除整份文件,可以使用下列语法。
delete(1.0,END)

注意:以上皆需要由Text对象启动。接下来将直接用程序实例讲解如何应用这些功能。

样例:使用tkinter设计具有/Cut/Copy/Paste功能的弹出菜单,这个菜单可以执行剪切/
复制/粘贴工作。

from tkinter import *
from tkinter import messagebox

def cutJob():
    copyJob()
    text.delete(SEL_FIRST,SEL_LAST)
def copyJob():
    try:
        text.clipboard_clear()
        copyText=text.get(SEL_FIRST,SEL_LAST)
        text.clipboard_append(copyText)
    except TclError:
        print("没有选取")

def pasteJob():
    try:
        copyText=text.selection_get(selection="CLIPBOARD")
        text.insert(INSERT,copyText)
    except TclError:
        print("剪贴板没有数据")
def showPopupMenu(event):
    popupmenu.post(event.x_root,event.y_root)

root=Tk()
root.title("ch17_18")
root.geometry("300x180")

popupmenu=Menu(root,tearoff=False)

popupmenu.add_command(label="Cut",command=cutJob)
popupmenu.add_command(label="Copy",command=copyJob)
popupmenu.add_command(label="Paste",command=pasteJob)

root.bind("<Button-3>",showPopupMenu)
root.config(menu=popupmenu)
text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Five Hunder Miles\n","a")
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")

root.mainloop()
image.png

上述Cut/Copy/Paste方法目前已经内建为tkinter的虚拟事件,可以直接引用,可参考下列
方法。

from tkinter import *
from tkinter import messagebox

def cutJob():
    text.event_generate("<<Cut>>")
def copyJob():
    text.event_generate("<<Copy>>")
def pasteJob():
    text.event_generate("<<Paste>>")
def showPopupMenu(event):
    popupmenu.post(event.x_root,event.y_root)

root=Tk()
root.title("ch17_18")
root.geometry("300x180")

popupmenu=Menu(root,tearoff=False)

popupmenu.add_command(label="Cut",command=cutJob)
popupmenu.add_command(label="Copy",command=copyJob)
popupmenu.add_command(label="Paste",command=pasteJob)

root.bind("<Button-3>",showPopupMenu)

text=Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Five Hunder Miles\n","a")
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")

root.mainloop()
image.png

复原与重复

Text控件由一个简单复原(undo)和重复(redo)的机制,这个机制可以应用于文字删除(delete)和
文字插入(insert)。Text控件在默认环境下没有开启这个机制,如果要使用这个机制,可以在
Text()方法内增加undo=True参数。

样例:怎该工具栏,在这个工具栏内有Undo和Redo功能按钮,可以分别执行Undo和Redo工作。

from tkinter import *
from tkinter import messagebox

def cutJob():
    text.event_generate("<<Cut>>")
def copyJob():
    text.event_generate("<<Copy>>")
def pasteJob():
    text.event_generate("<<Paste>>")
def showPopupMenu(event):
    popupmenu.post(event.x_root,event.y_root)
def undoJob():
    try:
        text.edit_undo()
    except:
        print("先前没有动作")
def redoJob():
    try:
        text.edit_redo()
    except:
        print("先前没有动作")

root=Tk()
root.title("ch17_18")
root.geometry("300x180")

popupmenu=Menu(root,tearoff=False)

popupmenu.add_command(label="Cut",command=cutJob)
popupmenu.add_command(label="Copy",command=copyJob)
popupmenu.add_command(label="Paste",command=pasteJob)

root.bind("<Button-3>",showPopupMenu)

toolbar=Frame(root,relief=RAISED,borderwidth=1)
toolbar.pack(side=TOP,fill=X,padx=2,pady=1)

undoBtn=Button(toolbar,text="Undo",command=undoJob)
undoBtn.pack(side=LEFT,pady=2)
redoBtn=Button(toolbar,text="Redo",command=redoJob)
redoBtn.pack(side=LEFT,pady=2)

text=Text(root,undo=True)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Five Hunder Miles\n","a")
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")

root.mainloop()
image.png

当我们在Text()构造方法中增加undo=True参数后,就可以用text对象调用edit_undo()方法,
这个方法会自动执行Undo动作。可以用text对象调用edit_redo()方法,这个方法会自动执行
Redo动作。

查找文字

在Text控件内可以使用search()方法查找指定的字符串,这个方法会传回找到第一个指定字符串
的索引位置。假设Text控件的对象是text,它的语法如下。
pos=text.search(key,startindex,endindex)

(1)pos:传回所找到的字符串的索引位置,如果查找失败则传回空字符串。
(2)key:所查找的字符串。
(3)startindex:查找起始位置。
(4)endindex:查找结束位置,如果查找到文档最后可以使用END。

样例:查找文字的应用,所查找的文字将用黄色底显示。

from tkinter import *
from tkinter import messagebox

def mySearch():
    text.tag_remove("found","1.0",END)
    start="1.0"
    key=entry.get()

    if (len(key.strip())==0):
        return
    while True:
        pos=text.search(key,start,END)
        if (pos==""):
            break
        text.tag_add("found",pos,"%s+%dc" % (pos,len(key)))
        start="%s+%dc" % (pos,len(key))

root=Tk()
root.title("ch17_21")
root.geometry("300x180")

root.rowconfigure(1,weight=1)
root.columnconfigure(0,weight=1)

entry=Entry()
entry.grid(row=0,column=0,padx=5,stick=W+E)

btn=Button(root,text="查找",command=mySearch)
btn.grid(row=0,column=1,padx=5,pady=5)

text=Text(root,undo=True)
text.grid(row=1,column=0,columnspan=2,padx=2,pady=5,
          sticky=N+S+W+E)
text.insert(END,"Five Hunder Miles\n","a")
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")
text.insert(END,"A hundred miles,\n")

text.tag_configure("found",background="yellow")

root.mainloop()
image.png

讲解:pos=text.search(key,start,END)
这个代码会查找key关键字,所查找的范围是text控件内容start索引至文件结束,若是查找到
会传回key关键字出现的索引位置给pos。
text.tag_add("found",pos,"%s+%dc" % (pos,len(key)))
start="%s+%dc" % (pos,len(key))
上述pos是加入标签的起始位置,标签的结束位置是一个索引的表达式。

上述是所查找到字符串的结束索引位置,相当于是pos位置加上key关键词的长度。
"%s+%dc" % (pos,len(key))
这里则是更新查找起始位置,为下一次查找做准备。

存储Text控件内容

在tkinter.filedialog模块中有asksaveasfilename()方法,我们可以使用次方法,让窗口
出现对话框,再执行存储工作。

filename=asksaveasfilename()
上述代码可以传回所存文档的路径(含文件夹)

样例:建立一个File菜单,再这个菜单内有Save As 命令,执行此命令可以出现"另存为"对话框,
然后可以选择文件夹以及输入文件名,最后存储文档。

from tkinter import *
from tkinter.filedialog import asksaveasfilename

def saveAsFile():
    global filename
    textContent=text.get("1.0",END)

    filename=asksaveasfilename(defaultextension=".txt")
    if filename=="":
        return
    with open(filename,"w") as output:
        output.write(textContent)
        root.title(filename)

filename="Untitiled"
root=Tk()
root.title("filename")
root.geometry("300x180")

menubar=Menu(root)

filemenu=Menu(menubar,tearoff=False)
menubar.add_cascade(label="File",menu=filemenu)

filemenu.add_command(label="Save As",command=saveAsFile)
filemenu.add_separator()
filemenu.add_command(label="Exit",command=root.destroy)
root.config(menu=menubar)

text=Text(root,undo=True)
text.pack(fill=BOTH,expand=True)
text.insert(END,"Five Hunder Miles\n","a")
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")
text.insert(END,"A hundred miles,\n")

root.mainloop()
image.png

打开文档

在tkinter.filedialog模块中有askopenfilename()方法,可以使用此方法,让窗口出现对话框,
再执行选择要打开的文档。

filename=askopenfilename()

上述代码可以传回所存盘文档的路径(含文件夹),然后可以使用open()方法打开文档,最后
将打开的文档插入Text控件。步骤如下。
(1)在打开对话框中选择欲打开的文档。
(2)使用open File()方法打开文档。
(3)使用read()方法读取文档内容。
(4)删除Text控件内容。
(5)将所读取的文档内容插入Text控件。
(6)更改窗口标题名称。

样例:

from tkinter import *
from tkinter.filedialog import asksaveasfilename
from tkinter.filedialog import askopenfilename

def newFile():
    text.delete("1.0",END)
    root.title("Untitled")

def openFile():
    global filename
    filename=askopenfilename()
    if filename=="":
        return
    with open(filename,"r") as fileObj:
        content=fileObj.read()
    text.delete("1.0",END)
    text.insert(END,content)
    root.title(filename)

def saveAsFile():
    global filename
    textContent=text.get("1.0",END)

    filename=asksaveasfilename(defaultextension=".txt")
    if filename=="":
        return
    with open(filename,"w") as output:
        output.write(textContent)
        root.title(filename)

filename="Untitiled"
root=Tk()
root.title("filename")
root.geometry("300x180")

menubar=Menu(root)

filemenu=Menu(menubar,tearoff=False)
menubar.add_cascade(label="File",menu=filemenu)

filemenu.add_command(label="New File",command=newFile)
filemenu.add_command(label="Open File ...",command=openFile)
filemenu.add_command(label="Save As ...",command=saveAsFile)
filemenu.add_separator()
filemenu.add_command(label="Exit",command=root.destroy)
root.config(menu=menubar)

text=Text(root,undo=True)
text.pack(fill=BOTH,expand=True)

root.mainloop()
image.png

默认含滚动条的ScrolledText控件

在tkinter.scrolledtext模块内有ScrolledText控件,这是一个默认含有滚动条的Text控件,
使用时可以先导入此模块,执行时就可以看到滚动条。

样例:

from tkinter import *
from tkinter.filedialog import asksaveasfilename
from tkinter.filedialog import askopenfilename
from tkinter.scrolledtext import ScrolledText

def newFile():
    text.delete("1.0",END)
    root.title("Untitled")

def openFile():
    global filename
    filename=askopenfilename()
    if filename=="":
        return
    with open(filename,"r") as fileObj:
        content=fileObj.read()
    text.delete("1.0",END)
    text.insert(END,content)
    root.title(filename)

def saveAsFile():
    global filename
    textContent=text.get("1.0",END)

    filename=asksaveasfilename(defaultextension=".txt")
    if filename=="":
        return
    with open(filename,"w") as output:
        output.write(textContent)
        root.title(filename)

filename="Untitiled"
root=Tk()
root.title("filename")
root.geometry("300x180")

menubar=Menu(root)

filemenu=Menu(menubar,tearoff=False)
menubar.add_cascade(label="File",menu=filemenu)

filemenu.add_command(label="New File",command=newFile)
filemenu.add_command(label="Open File ...",command=openFile)
filemenu.add_command(label="Save As ...",command=saveAsFile)
filemenu.add_separator()
filemenu.add_command(label="Exit",command=root.destroy)
root.config(menu=menubar)

text=ScrolledText(root,undo=True)
text.pack(fill=BOTH,expand=True)

root.mainloop()

插入图像

from tkinter import *
from PIL import Image,ImageTk

root=Tk()
root.title("ch17_29")

img=Image.open("hung.jpg")
myPhoto=ImageTk.PhotoImage(img)

text=Text()
text.image_create(END,image=myPhoto)
text.insert(END,"\n")
text.insert(END,"略")
text.pack(fill=BOTH,expand=True)

root.mainloop()

ScrolledText.see(index):
索引指向的字符处于滚动条的可见范围内

相关文章

  • 十七、文字区域Text

    文字区域Text的基本概念 Text的构造方法如下。Text(父对象,options,···) Text()方法的...

  • 微信小程序 <button 中多行文本、文字换行

    button中文字换行 {{data1}}{{data2}} ...

  • Flutter UI基础- Text

    文字显示控件 Text, Text.rich Text 相关属性: Text.rich 相关属性: 很明显这两个控...

  • Flutter基础控件之Text

    Text定义 Text是flutter中用来显示文字的小部件。 Text的类型是StatelessWidget。构...

  • text被挤出显示区域

    有这样一种需求 限定一行展示商品名称和商品的价格。当商品名称过长时,价格则有可能显示不下。需求是:商品价格展示第一...

  • canvas(一)

    文字方法 strokeText(text, x, y) 描边写字 fillText(text, x, y) ...

  • canvas day-03

    文字 strokeText(text, x, y) fillText(text. x, y) font textA...

  • canvas写字插图

    文字方法 strokeText(text, x, y) 描边写字 fillText(text, x, y) ...

  • canvas简单入门(2)

    文字方法 strokeText(text, x, y) 描边写字 fillText(text, x, y) ...

  • 1.呈现文字的属性 text 返回值类型是NSString lable.text=@"shieng"; 2.文字的...

网友评论

      本文标题:十七、文字区域Text

      本文链接:https://www.haomeiwen.com/subject/yqezqktx.html