在Tkinter文本部件中交换行
我已经把所有东西都设置好了,但就是不知道怎么在Tkinter的文本控件中交换两行。这个文本控件是禁用的,而且里面的内容是由其他控件填充的,所以我给这个禁用的文本控件加了一些功能,做了三个按钮:向上移动、向下移动和删除。删除功能已经实现了,但我还搞不定另外两个按钮。现在我正在处理两个值,分别表示要修改的文本行的开始和结束位置: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
的值来交换当前行和它前面或后面的那一行。
3 个回答
这段代码的意思是:删除从“插入点的行开始”到“插入点的行结束”的文本。具体来说,它会删除光标所在行的内容。这里的“Move_down delete”可能是指向下移动光标并删除内容的操作。
根据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
方法获取小部件中任何位置的索引。这个方法可以接收一些参数,比如 linestart
和 lineend
,这些都是用来指定行的开始和结束位置的。你还可以用类似 +1c
的方式来获取下一个字符的索引,或者用 +1l
来获取下一行的索引。此外,你也可以使用 wordstart
和 wordend
来获取单词的起始和结束位置。你可以把这些组合在一起使用,比如: index("insert lineend +1c")
举个例子,如果你想获取插入光标所在行的开始和结束位置(这里的 'insert' 是表示插入光标的标记名称):
start = self.TextWidg("insert linestart")
end = self.TextWidg("insert lineend")
想了解更多信息,可以查看 effbot.org 上的文本小部件页面 中的“表达式”部分。