一.文本基础
from tkinter import *
root = Tk()
text1 = Text(root,width=30,height=2)
text1.pack()
text1.insert(INSERT,'I love \n')
text1.insert(END,'ljj')
mainloop()
width=30,height=2
是30个字符的长度,两行
text1.insert(INSERT,'I love \n')
中的INSERT
是指在光标的位置插入
二.插入其他组件
1.1 插入按钮
from tkinter import *
root = Tk()
text1 = Text(root,width=30,height=5)
text1.pack()
text1.insert(INSERT,'I love \n')
text1.insert(END,'ljj')
def show():
print('我被点了一下')
b1 = Button(text1,text='点我',command=show)
text1.window_create(INSERT,window=b1)
mainloop()
b1 = Button(text1,text='点我',command=show)
这一句参数没有写root
是因为这个组件时插入在text1
上的
text1.window_create(INSERT,window=b1)
是因为button
是窗口组件
1.2 插入图片
from tkinter import *
root = Tk()
text1 = Text(root,width=50,height=100)
text1.pack()
photo = PhotoImage(file='p.gif')
def show():
text1.image_create(END,image=photo)
b1 = Button(text1,text='点我',command=show)
text1.window_create(INSERT,window=b1)
mainloop()
text1.image_create(END,image=photo)
图片不是窗口组件,是一个图片组件
三.text其他函数
1. get
text.get(1.2)这个是指第一行第三列
行是从1开始,列是从0开始
from tkinter import *
root = Tk()
text1 = Text(root,width=50,height=5)
text1.pack()
text1.insert(INSERT,'I love ljj')
print(text1.get(1.2,1.5))
mainloop()
1.2 是 l,1.5是 e
这个只有一行,所以不能直接写2.1,但可以用空格补充
如果是get(1.2,1.end)
表示从1.2开始,第一行打印完
2.mark
from tkinter import *
root = Tk()
text1 = Text(root,width=50,height=5)
text1.pack()
text1.insert(INSERT,'I love ljj')
text1.mark_set('here',1.2)
text1.insert('here','插')
mainloop()
text1.mark_set('here',1.2)
做一个名字叫here
的标记在1.2处
text1.insert('here','插')
在here
这插入一个“插”字
使用text1.mark_unset('here')
取消mark
的标记,之后就不能使用这个here
的标记了
3.撤销
from tkinter import *
root = Tk()
text1 = Text(root,width=50,height=5,undo=True)
text1.pack()
text1.insert(INSERT,'I love ljj')
def show():
text1.edit_undo()
Button(root,text='撤销',command=show).pack()
mainloop()
只用在text1 = Text(root,width=50,height=5,undo=True)
加入undo=True
最后在show
函数中加text1.edit_undo()
4.搜索
from tkinter import *
root = Tk()
text1 = Text(root,width=50,height=5,undo=True)
text1.pack()
text1.insert(INSERT,'I love ljj')
def getIndex(text,pos):
return tuple(map(int,str.split(text.index(pos),'.')))
start = "1.0"
while True:
pos = text1.search('j',start,stopindex=END)
if not pos:
break
print('找到了,位置是:',getIndex(text1,pos))
start = pos + '+1c'
mainloop()
这里getIndex
函数中,tuple(map(int,str.split(text.index(pos),'.')))
首先用text.index(pos)
将search
函数返回的line.column
索引类型变成str
型
再用str.split(text.index(pos),'.')
将这个字符串用.
分割成line
和column
最后用map
转成int
型,最后转成tuple
元组
最后的start = pos + '+1c'
中的‘+1c’
表示在当前位置向后移动1位,‘+5c’
表示向后移动5位