交换文本窗口中的行

2024-06-25 23:16:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经准备好了,只是不知道如何在Tkinter文本小部件中交换两行。它被禁用并由其他小部件填充,所以我给了禁用/未聚焦文本小部件一些功能,有3个按钮:上移、下移和删除。我已经删除了工作,但不知道如何让另外两个工作。现在我正在处理两个引用要修改的文本行的开始和结尾的值:self.line_start和{}

到目前为止我得到的是:

def Move_Up(self):
   self.TextWidg.config(state='normal')
   #swap this line with the line above it
   self.TextWidg.config(state='disabled')

def Move_Down(self):
   self.TextWidg.config(state='normal')
   #swap this line with the line below it
   self.TextWidg.config(state='disabled')

def Delete(self):
   self.TextWidg.config(state='normal')
   #delete the line
   self.TextWidg.delete(self.line_start,self.line_end)
   #delete the carriage return
   self.TextWidg.delete(self.line_start)
   self.TextWidg.config(state='disabled')

基本上,我如何实现self.line_startself.line_end的值来交换行与它前面的行或后面的行。在


Tags: the文本selfconfigmove部件defline
2条回答

根据Bryan的建议,我能够解决Move_Up()和Move_Down()方法,如下所示。它可以在macosx上使用python3.1.3或2.6.6

#swap this line with the line above it
def Move_Up():
    text.config(state='normal')
    # get text on current and previous lines
    lineText = text.get("insert linestart", "insert lineend")
    prevLineText = text.get("insert linestart -1 line", "insert -1 line lineend")

    # delete the old lines
    text.delete("insert linestart -1 line", "insert -1 line lineend")
    text.delete("insert linestart", "insert lineend")

    # insert lines in swapped order
    text.insert("insert linestart -1 line", lineText)
    text.insert("insert linestart", prevLineText)
    #text.config(state='disabled')


#swap this line with the line below it
def Move_Down():
    text.config(state='normal')
    # get text on current and next lines
    lineText = text.get("insert linestart", "insert lineend")
    nextLineText = text.get("insert +1 line linestart", "insert +1 line lineend")

    # delete text on current and next lines
    text.delete("insert linestart", "insert lineend")
    text.delete("insert +1 line linestart", "insert +1 line lineend")

    # insert text in swapped order
    text.insert("insert linestart", nextLineText) 
    text.insert("insert linestart + 1 line", lineText)
    #text.config(state='disabled')

编辑:请注意,如果只有一行文本,Move_Up()会将该文本附加到该行。如果只有一行,Move_Down()什么也不做。在

您可以使用index方法获得小部件中任何位置的索引。您可以给它一个包含修饰符的参数,比如linestartlineend。您也可以使用类似+1c的方法获取相对位置的索引,以获得下一个字符的索引,或者使用+1l来获取下一行。您还可以使用wordstartwordend。您可以组合它们,例如:index("insert lineend +1c")

例如,要获取具有插入光标的行的起点和终点(其中“insert”是表示插入光标的标记的名称):

start = self.TextWidg("insert linestart")
end = self.TextWidg("insert lineend")

有关详细信息,请参阅text widget page on effbot.org上标题为“表达式”的部分。在

相关问题 更多 >