无法使用mark_set小部件函数移动文本'insert'索引(Python和Tkinter)

1 投票
2 回答
1930 浏览
提问于 2025-04-18 09:05

我一直在尝试强制将“插入”光标移动到文本框的开头,不管用户在文本框的哪个地方点击。虽然我找到了一篇相关的帖子,这个帖子,但在我的代码中似乎不起作用。光标/插入点还是停留在我点击的位置(注意:其他功能都正常)。最后我尝试了“return 'break'”,想看看是否有其他功能在运行时“恢复”了光标的位置,但没有任何变化。我使用的是Python 3.4和Tkinter 8+。谢谢你们!!

...
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)

2 个回答

0

问题在于,默认情况下,点击的地方会让光标移动。你的代码没有覆盖这个默认行为,所以光标先被你移动了一次,然后默认行为又把它移动了一次。如果你想了解更深层次的解释,可以搜索一下“bind tags”或者“bindtags”。

要阻止这个默认行为发生,你需要在你的函数中返回一个字符串 "break",这样就可以停止事件的进一步处理:

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

我觉得你应该把你的文本绑定到 <ButtonRelease-1> 事件上,而不是 <1><Button-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()

我猜原因是,Tkinter 在执行绑定到 <Button-1> 的时候,会把光标设置在点击的位置,而绑定到 <ButtonRelease-1> 时就不会这样。希望这能帮到你。

撰写回答