python笔记(二十八) tkinter(6) 文本

一.文本基础

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),'.')将这个字符串用.分割成linecolumn
最后用map转成int型,最后转成tuple元组

最后的start = pos + '+1c'中的‘+1c’表示在当前位置向后移动1位,‘+5c’表示向后移动5位
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值