2012-03-31 96 views
1

我希望能够在Tkinter Text小部件中双击test,
,并让它选择测试(并排除逗号)。如何修改Tkinter Text小部件中的当前选择长度?

这里是我试过:

import Tkinter as tk 

def selection_mod(event=None): 
    result = aText.selection_get().find(',') 
    if result > 0: 
     try: 
      aText.tag_add("sel", "sel.first", "sel.last-1c") 
     except tk.TclError: 
      pass 

lord = tk.Tk() 

aText = tk.Text(lord, font=("Georgia", "12")) 
aText.grid() 

aText.bind("<Double-Button-1>", selection_mod) 

lord.mainloop() 

的第一个问题是<Double-Button-1>似乎触发处理程序作出选择之前,生产:

TclError: PRIMARY selection doesn't exist or form "STRING" not defined

第二个问题是,即使使用有效的绑定,
我的选择标签似乎没有做任何事情。
它甚至没有提出错误,我试过没有except tk.TclError:

回答

1

您的绑定发生在默认绑定发生之前。因此,当您的绑定触发时,选择不存在。由于您的绑定尝试获取选择,因此会失败并显示您看到的错误。

您将需要安排绑定在类绑定之后发生。一个便宜的黑客就是使用after来执行你的代码,一旦默认绑定有机会工作。或者,您可以使用bindtag功能确保您的绑定在默认绑定之后触发。

第二个问题是,在设置新设置之前,您不清除旧选择。您需要执行tag_remove以首先删除现有的选择。否则,逗号(如果以某种方式选中)将保持选中状态,因为您所做的只是将标签重新应用于已有标签的文本。

但是,双击通常不会捕获逗号,所以我不太理解您的代码的重点。至少,当我在OSX上测试它时,它不包含逗号。

1

这里是我想出了感谢布莱恩的回答是:

import Tkinter as tki # tkinter in Python 3 

def selection_mod(event=None): 
    result = txt.selection_get().find(',') 
    if result > 0: 
     fir, sec = txt.tag_ranges("sel") 
     txt.tag_remove("sel", "sel.first", "sel.last") 
     txt.tag_add("sel", fir, str(sec)+"-1c") 

root = tki.Tk() 

txt = tki.Text(root, font=("Georgia", "12")) 
txt.grid() 

txt.bind("<Double-Button-1>", lambda x: root.after(20, selection_mod)) 

root.mainloop() 

值得一提的是,我使用的是Windows 7,并根据布莱恩,
OSX没有你的时候包含逗号双击一个字。

+0

我最近发现了如何设置用tcl选择的字符。 [链接](http://stackoverflow.com/a/28133301/1217270) – 2015-01-26 23:17:04

相关问题