【问题标题】:Python - .insert() method only replaces the first letter of word?Python - .insert() 方法只替换单词的第一个字母?
【发布时间】:2021-02-08 07:23:07
【问题描述】:

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

代码如下:

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'。任何帮助表示赞赏!

【问题讨论】:

  • 你做了什么来调试这个?您是否已验证 indexlast_idx 是您所假设的?

标签: python tkinter desktop-application


【解决方案1】:

你有两个问题。

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

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

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

【讨论】:

  • (更新了我的答案。我才发现wordshortcut有同样的问题)
  • 成功了!我对 Python 有点陌生,不知道字符串可以这么细致。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
相关资源
最近更新 更多