python - 无法使用 mark_set 小部件功能移动文本 'insert' 索引(Python 和 Tkinter)

标签 python text tkinter

我一直在尝试强制“插入”标记移动到文本字段的开头,无论用户在该字段上单击什么位置。虽然我发现this post ,它似乎在我的代码中不起作用。光标/插入只是停留在我单击的索引处(注意:函数的其余部分工作正常)。作为最后一个想法,我尝试“返回'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)

最佳答案

我认为您应该将文本绑定(bind)到 <ButtonRelease-1>事件,而不是<1><Button-1> 。在这个简单的测试示例中,绑定(bind)到 <Button-1>不会移动鼠标光标。但是,如果您绑定(bind)到 <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在绑定(bind)到<Button-1>后将光标设置在点击位置被执行,绑定(bind)到 <ButtonRelease-1> 时则不然。希望这会有所帮助。

关于python - 无法使用 mark_set 小部件功能移动文本 'insert' 索引(Python 和 Tkinter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113946/

相关文章:

python - 通过 python 接口(interface)传递 cython 函数

python - 排序值,类型错误 : '<' not supported between instances of 'numpy.ndarray' and 'str'

ruby - 使用 vim,是否有命令自动换行粘贴文本?

python - geometry() 中的 +0+0 在 tkinter 中是什么意思?

python - 删除 tkinter TreeView 中的标题行

python - numpy/pylab 最小值,最大值

python - Pygame 绘制错误

python - 如何在 python 中允许多行用户输入?

javascript - 编辑文本图层 - Photoshop 脚本

python - 如何在 .local 中安装 tkinter