有人能回答为什么在下面的代码中命令self.text.mark_previous(self.text.index("insert"))
工作并返回正确的标记,而self.text.mark_previous("insert")
返回tk::anchor1
吗?只需点击文本中的一个区域并点击按钮。你知道吗
import tkinter as tk
class Main(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.text = tk.Text()
self.text.pack()
self.strings = ["Region 1", "Region 2", "Region 3"]
for text in self.strings:
self.text.mark_set(text, "insert")
self.text.mark_gravity(text, "left")
self.text.insert("insert", "{}\n".format(text))
for mark in self.strings:
print(self.text.index(mark))
self.button = tk.Button(text="Find Region", command=self.find_region)
self.button.pack()
def find_region(self):
self.text.update_idletasks()
region = self.text.mark_previous("insert") # This doesn't work. It returns tk::anchor1
region2 = self.text.mark_previous(self.text.index("insert")) # This works
print("You are in region {} {}".format(region, region2))
if __name__ == '__main__':
main = Main()
main.mainloop()
答案是,在处理标记时,特金特并不认为
"insert"
和index("insert")
是一回事。从文本的角度来看,它们是相同的,但是从文本小部件管理的所有其他数据的角度来看,它们是不同的。你知道吗考虑一个文本小部件,在第1行有文本“Hello,world”。当您单击字母“w”时,会发生一些事情:tkinter将添加标记“insert”、“tk::anchor1”和“current”。这些标记是订购的。如果要将文本小部件内容转换为xml,它可能如下所示:
调用
mark_previous("1.7")
时,索引“1.7”指的是紧靠字母“w”之前的点和所有标记之后的点。因此,当您请求上一个标记时,它将返回“insert”,因为这是紧靠字母“w”左侧的内容。但是,如果您要求使用“insert”之前的标记而不是“1.7”,您将得到“tk::anchor1”,因为它是“insert”标记左侧的标记。你知道吗您可以使用文本小部件
dump
方法查看标记和数据的顺序。它以列表而不是xml的形式返回信息,但它允许您查看文档的内部结构。你知道吗继续使用相同的示例(“Hello,world”,在单击“w”之前,
dump
方法返回以下内容(为了清楚起见,我添加了新行):如您所见,标记“current”位于标记“tk::anchor1”之前,该标记位于“insert”之前,该标记位于“world”中的字母“w”之前。你知道吗
因为在与
insert
相同的索引处有一个标记tk::anchor#
,但在前面的位置最初或当鼠标指针不在任何文本上时,
current
和insert
标记位于同一索引处,顺序为current
,后跟insert
。你知道吗如果你在程序开始时点击“查找区域”按钮,它就会打印出来
因为按顺序,
current
标记在insert
标记之前的位置(但在同一索引处),但Region 3
标记在insert
标记之前的“索引”处。你知道吗据我所知,tkinter在您第一次单击文本框时添加了一个额外的标记
tk::anchor#
(我还不知道原因),该标记与insert
位于同一索引,但就在insert
标记之前(如果鼠标指针不在文本上,则在current
之后)。你知道吗因此,当您根据标记的名称而不是索引搜索上一个标记时,将返回同一索引上的上一个标记。您可以通过在同一索引中添加两个用户定义的标记来测试它。
相关问题 更多 >
编程相关推荐