【问题标题】:Removing duplicate lines in tkinter text widget删除 tkinter 文本小部件中的重复行
【发布时间】:2021-03-15 18:44:16
【问题描述】:

有什么方法可以去除 tkinter 中的重复行吗?

代码如下:

from tkinter import *

root = Tk()

def remove_duplicate():
    # Code to remove all duplicate lines in the text widget
    pass

text = Text(root , width = 65,  height = 20, font = "consolas 14")
text.pack()

text.insert('1.0' , '''Hello world\n\nHello world\n\nBye bye\n\n\n\n\nBye bye\nBye bye''')

remove_button = Button(root , text = "Remove Duplicate Lines" , command = remove_duplicate)
remove_button.pack()

mainloop()

当我点击remove_button 时,我希望删除文本小部件中的所有重复行。

在这种情况下,我有字符串:

"""
Hello world

Hello world

Bye bye




Bye bye
Bye bye
"""

,所以当我删除重复的行时,我应该得到类似的东西:

"""
Hello world

Bye bye
"""

有没有办法在 tkinter 中实现这一点?

如果有人能帮助我,那就太好了。

【问题讨论】:

  • 获取文本作为字符串,对其进行操作(this 可能有用),然后将其放回<tk.Text>
  • stackoverflow 上有很多关于从列表中删除重复项的问题,并且文本小部件实际上是一个字符串列表。您是否研究过如何从字符串列表中删除重复项?
  • @BryanOakley:是的,我尽我所能,但没有成功。

标签: python tkinter duplicates


【解决方案1】:

基本思想是获取小部件中的所有文本,删除重复项并添加到新列表中。现在将新的列表项添加到文本小部件,例如:

def remove_duplicate():
    val = text.get('0.0','end-1c').split('\n') # Initial values
    dup = [] # Empty list to append all non duplicates
    text.delete('0.0','end-1c') # Remove currently written words
    
    for i in val: # Loop through list
        if i not in dup: # If not duplicate
            dup.append(i) # Append to list
            dup.append('\n') # Add a new line

    text.insert('0.0',''.join(dup)) # Add the new data onto the widget
    text.delete('end-1c','end') # To remove the extra line.

我已经用 cmets 解释了它,以便在旅途中理解。这看起来很简单,尽管我相信它可以进一步优化。

【讨论】:

  • 再次感谢@CoolCloud 的快速回答,但我面临一个小问题。当我运行这个函数时,最后会有一些不必要的空行。有什么办法可以去掉那些空行吗?
  • @Lenovo360 尝试在func末尾添加text.delete('end-1c','end')
  • @Lenovo360 我还删了几行,看看吧。
  • 文本小部件中的第一个字符是"1.0",而不是"0.0"
  • @BryanOakley "1.0" 与 tcl 解释器的 "0.0" 相同
猜你喜欢
  • 1970-01-01
  • 2019-06-14
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
相关资源
最近更新 更多