我正在实现一个基于 tkinter 文本小部件的控制台应用程序,作为自动完成功能的一部分,我观察到一个问题,即按下返回键会导致删除所选文本。下面的示例显示了类似的问题:
from Tkinter import *
def getCommand(*args):
global text
text.insert(END, "\n")
text.insert(END, "command>")
x = text.get("1.0",END)
print "command is %s" %(x)
return 'break'
def handle_keyrelease(event):
global text
if event.keysym == "Return":
text.tag_remove(SEL,"1.9",END)
text.mark_set("insert",END)
getCommand()
return 'break'
root = Tk()
text = Text(root)
text.pack()
text.insert(END,"command>")
text.focus()
text.bind("<KeyRelease>", handle_keyrelease)
text.insert(END,"sometext")
text.tag_add(SEL,"1.9",END)
text.mark_set("insert","1.9")
root.mainloop()
在这段代码中,当我按回车键时,我想获得完整的命令sometext
,但是只s
检索当前代码。当收到返回键事件时,我尝试将光标位置设置为结束并删除选择标签。
编辑
KeyPress
事件处理程序的问题:
from Tkinter import *
def getCommand(*args):
global text
text.insert(END, "\n")
text.insert(END, "command>")
x = text.get("1.0",END)
print x
return 'break'
validkeysymchars = []
validkeysymchars = validkeysymchars + map(chr, range(65,91))
validkeysymchars = validkeysymchars + map(chr, range(97,123))
def handle_keyrelease(event):
global text
if event.keysym == "Return":
text.tag_remove(SEL,"1.9",END)
text.mark_set("insert",END)
getCommand()
return 'break'
if event.keysym in validkeysymchars:
for x in ['testcommand']:
strtocmp = text.get("MARK","end")
strtocmp = strtocmp.encode('ascii','ignore')
strtocmp = strtocmp.strip()
print strtocmp
if x.startswith(strtocmp):
currpos = text.index(INSERT)
text.insert(END,x[len(strtocmp):])
text.tag_add(SEL,currpos,"%s+%dc"%(currpos,len(x)-len(strtocmp)))
text.mark_set("insert",currpos)
root = Tk()
text = Text(root)
text.pack()
text.insert(END,"command>")
text.mark_set("MARK",INSERT)
text.mark_gravity("MARK",LEFT)
text.focus()
text.bind("<KeyPress>", handle_keyrelease)
root.mainloop()