[英]Swapping lines in a Tkinter text widget
我已经设置好了一切,我只是不知道如何在 Tkinter 文本小部件中交换 2 行。 它被其他小部件禁用和填充,因此我为禁用/未聚焦的文本小部件提供了一些带有 3 个按钮的功能; 上移、下移和删除。 我已经删除了工作,但不知道如何让其他两个工作。 现在我正在处理 2 个引用要修改的文本行的开头和结尾的值: self.line_start
和self.line_end
这是我到目前为止所拥有的:
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_start
和self.line_end
值以将行与其之前的行或之后的行交换。
按照 Bryan 的建议,我能够按如下方式解决 Move_Up() 和 Move_Down() 方法。 它在 Mac OS X 上使用 Python 3.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
方法获取小部件中任何位置的index
。 您可以给它一个包含修饰符的参数,例如linestart
和lineend
。 您还可以使用诸如+1c
类的东西来获取相对位置的索引以获取下一个字符的索引,或者使用+1l
来获取下一行。 您还可以使用wordstart
和wordend
。 您可以将它们组合起来,例如: index("insert lineend +1c")
例如,要获取具有插入光标的行的开头和结尾(其中 'insert' 是代表插入光标的标记的名称):
start = self.TextWidg("insert linestart")
end = self.TextWidg("insert lineend")
有关更多信息,请参阅effbot.org上文本小部件页面上标题为“表达式”的部分。
text.delete("insert linestart +0 line","insert +0 line lineend") Move_down delete
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.