Wxpython textctrl索引位置错乱,换行符问题

在Textctrl中输入带有换行的文本,通过自定义的搜索函数,会出现索引错误的问题,以下是我的原来的代码

def search_text(self, event):
    print('搜索文本!')
    keyword = event.GetString()
    if keyword == self.pre_keyword:
        if self.pre_search_selection == len(self.search_result)-1:
            self.pre_search_selection = 0
        else:
            self.pre_search_selection += 1
    else:
        self.pre_keyword = keyword
        text = self.text.GetValue()
        self.search_result = [i.span() for i in re.finditer(keyword, text)]
        self.pre_search_selection = 0

    if self.search_result:
        info_text = '{0}/{1}个匹配项'.format(str(self.pre_search_selection+1), str(len(self.search_result)))
        self.search_info.SetLabelMarkup("<span color='GREY'>"+info_text+"</span>")
        self.text.SetSelection(*self.search_result[self.pre_search_selection])
    else:
        info_text = '0个匹配项'
        self.search_info.SetLabelMarkup("<span color='GREY'>" + info_text + "</span>")
        self.text.SetSelection(0,0)

主要用到的是self.text.GetValue()来获取输入框中的文本,然后用SetSelection来选择re.finditer找到的索引位置。可是实际索引却会把\n识别为两个字符
这是因为windows系统下和Unix系统下换行符的不一致,windows是\r\n而Unix则是\n这个问题在Wxpython的官方文档中也有提到
因此我们把文本内容中的换行符全部替换为\r\n即可

text = self.text.GetValue()
text = text.replace('\r\n','\n') #为了防止反复被替换,先统一
text = text.replace('\n','\r\n')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值