首页 > 解决方案 > Python - .insert() 方法只替换单词的第一个字母?

问题描述

我之前已经发布过这个问题,并且我已经能够将程序缩减为一个用于测试目的的函数。我没有收到任何错误,但我遇到了一个让我陷入困境的错误。我可以替换快捷方式,但它只替换快捷方式的第一个字母。

这是代码:

from tkinter import *

root = Tk()
text = Text(root)
text.pack(expand=1, fill=BOTH)

syntax = "shortcut = sc" # This will be turned into a function to return the shortcut
                         # and the word, I'm only doing this for debugging purposes.

def replace_shortcut(event=None):
    tokens = syntax.split()
    word = tokens[:1]
    shortcut = tokens[2:3]

    index = '1.0'
    while 1:
        index = text.search(shortcut, index, stopindex="end")
        if not index: break
        
        last_idx = '%s + %dc' % (index, len(shortcut))
        
        text.delete(index, last_idx)
        text.insert(index, word)
        
        last_idx = '%s + %dc' % (index, len(word))

text.bind('<space>', replace_shortcut)
text.mainloop()

给定的快捷方式,在我们的例子中,'sc' 将在输入空格后变成 'shortcutc'。任何帮助表示赞赏!

标签: pythontkinterdesktop-application

解决方案


你有两个问题。

您将变量shortcut定义为['sc']而不是'sc'. 所以len(shortcut)总是 1(数组的长度)而不是 2(字符串的长度)。你最终只会删除一个字符。可能你想要len(shortcut[0])

[你也有同样的问题len(word)。您将始终得到 1,即数组的长度。]

此外,您的 while 循环的最后一行应该设置index而不是last_idx,因为这是将在下一次搜索中使用的变量。


推荐阅读