无法使用mark_set widget函数(Python&Tkinter)移动文本“insert”索引

2024-03-29 15:28:38 发布

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

我一直试图强制“insert”标记移动到文本字段的开头,而不管用户单击该字段的位置。虽然我找到了this post,但它在我的代码中似乎不起作用。光标/插入只停留在我单击的索引处(注意:函数的其余部分工作正常)。最后,我尝试了“return‘break’”,以防运行一些“恢复”光标位置的函数,但这没有什么区别。我使用的是python3.4和tkinter8+。谢谢你!!在

...
n = ttk.Notebook(p)
n1 = Text(n,width=60,height=15);
...
def EnterStatement(e):
    i=n1.index('current').split('.')
    n1.tag_remove('NewStatement', i[0]+'.0', i[0]+'.0 lineend')
    n1.replace(i[0]+'.16', i[0]+'.46', ' '*30,'flex')
    #the following doesn't work... why?!
    n1.mark_set('insert', i[0]+'.16')
...
n1.tag_bind("NewStatement",'<1>', EnterStatement)

Tags: 函数代码用户标记文本returntagthis
2条回答

我认为您应该将文本绑定到<ButtonRelease-1>事件,而不是<1>或{}。在这个简单的测试示例中,绑定到<Button-1>将不会移动鼠标光标。但是,如果绑定到<ButtonRelease-1>,则每次单击鼠标时,鼠标光标将移到开头。在

from tkinter import *


root = Tk()
text = Text(root)
text.insert(INSERT, "Some example text.\n Some second line of example text")

def onclick(event):
    #print(event)
    event.widget.mark_set(INSERT, '1.0')

text.bind('<ButtonRelease-1>', onclick)
#text.bind('<Button-1>', onclick)

text.pack()


root.mainloop()

我想原因是,在执行绑定到<Button-1>之后,Tkinter将光标设置在单击位置,而绑定到<ButtonRelease-1>时则不是这样。希望这有帮助。在

问题是,默认行为是将光标移动到单击的位置。绑定不会覆盖默认行为,因此代码会移动它,然后默认值会再次移动它。如果您搜索“bindtags”和/或“bindtags”,您可以找到更深入的解释。在

要防止发生默认行为,必须从函数返回字符串"break",这将停止进一步处理事件:

def EnterStatement(e):
    ...
    #the following doesn't work... why?!
    n1.mark_set('insert', i[0]+'.16')
    return "break"

相关问题 更多 >