Tkinter 认识Text的索引

Tkinter 认识Text的索引

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

(1)line/column("line.column"):计数方式line是从1开始,column从0开始计数,中间用句点分隔。

(2)INSERT:目前插入点的位置。

(3)CURRENT:光标目前位置相对于字符的位置。

(4)END:缓冲区最后一个字符后的位置。

(5)表达式Expression:索引使用表达式。

  • “+count chars”,count是数字,例如,“+2c”索引往后移动两个字符。
  • “-count chars”,count是数字,例如,“-2c”索引往前移动两个字符。

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

示例1

同时将所选的文字以常用的“line.column”字符串方式显示。

from tkinter import * 

def selectedText():
    try:
        selText = text.get(SEL_FIRST,SEL_LAST)
        print("Select text:",selText)
        # print("SEL_FIRST:",type(SEL_FIRST),"  SEL_LAST:",SEL_LAST)
        print("selectionStart:",text.index(SEL_FIRST))
        print("selectionEnd:",text.index(SEL_LAST))
    except TclError:
        print("No text selected")

root = Tk()
root.title("apidemos.com")
root.geometry("300x180")

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

# 建立Text
text = Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Love You Like A Love Song") # 插入文字

root.mainloop()

输出:

Tkinter 认识Text的索引

示例2

列出INSERT、CURRENT、END的位置。

from tkinter import * 

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

root = Tk()
root.title("apidemos.com")
root.geometry("300x180")

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

# 建立Text
text = Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Love You Like A Love Song\n") # 插入文字
text.insert(END,"apidemos.com") # 插入文字

root.mainloop()

输出:

Tkinter 认识Text的索引

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

示例3

在指定索引位置插入文字。

from tkinter import * 

root = Tk()
root.title("apidemos.com")
root.geometry("300x180")

# 建立Text
text = Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Love You Like A Love Song\n") # 插入文字
text.insert(1.14,"apidemos.com") # 插入文字

root.mainloop()

输出:

Tkinter 认识Text的索引

上述程序的重点是在line=1,column=14位置插入“apidemos.com”。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程