【问题标题】:How to find line number of searched string in Tkinter Textbox and then insert string just before如何在 Tkinter 文本框中查找搜索字符串的行号,然后在之前插入字符串
【发布时间】:2021-07-29 14:31:07
【问题描述】:

假设我有一个像这样的 tkinter 文本框:

文本框 =

Hello world !
Life is good on earth
Winter is already there

我如何搜索"good",获取行号并在行号之前插入一些内容?

预期结果:

Hello world !
New sentence inserted here
Life is good on earth
Winter is already there

我知道如何使用.find("good") 方法在达到“好”之前获取字符数,但由于我希望能够使用textbox.insert() 我需要行号(而不是字符数)像1.0 指定我想在文本框中插入新句子的位置。

【问题讨论】:

    标签: python tkinter textbox line


    【解决方案1】:

    您可以使用 tkinter 索引:

    from tkinter import *
     
    root = Tk()
    fram = Frame(root)
    Label(fram,text='Text to find:').pack(side=LEFT)
    edit = Entry(fram)
    edit.pack(side=LEFT, fill=BOTH, expand=1)
    edit.focus_set()
    butt = Button(fram, text='Find') 
    butt.pack(side=RIGHT)
    fram.pack(side=TOP)
    text = Text(root)
    text.insert('1.0','''Hello world !
    Life is good on earth
    Winter is already there''')
    text.pack(side=BOTTOM)
     
    def find():
        s = edit.get()
        if s:
            idx = '1.0'
            idx = text.search(s, idx, nocase=1, stopindex=END)
            if idx:
                text.insert(idx.split('.')[0]+'.0', 'New sentence inserted here\n')
        edit.focus_set()
    butt.config(command=find) 
    root.mainloop()
    

    【讨论】:

      【解决方案2】:

      您可以使用linestart 修改索引以获取行首。

      例如,假设变量index包含匹配的字符位置,比如2.8,可以这样获取行首:

      f"{index} linestart"  # eg: "2.8 linestart"
      

      在您的代码中,它可能看起来像这样:

      index = text.search("good", "1.0", "end")
      text.insert(f"{index} linestart", "New sentence inserted here\n")
      

      【讨论】:

        猜你喜欢
        • 2020-08-25
        • 2012-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        相关资源
        最近更新 更多