2016-01-13 26 views
0

我正在使用TkInter中的文本小部件功能來「保存」行/段落並追加到列表中。避免訪問相同的位置兩次/單擊兩次,TkInter文本小部件

with open(fname1, "rt", encoding='latin1') as in_file: 
    readable_file = in_file.read() 

line_list = [] 


def grab_line(event): 
    line_beginning = textPad.index("current linestart") 
    line_ending = textPad.index("current lineend") 
    line = textPad.get(line_beginning, line_ending) 
    line_list.append(line) 

root = Tk() 
frame = Frame(root, width=750, height=1) 
root.minsize(600,600) # sets the size of the actual window 
frame.pack() 
text = Text(root) 
text.insert(1.0, readable_file) 
text.bind('<Button-1>', grab_line) 
root.mainloop() 

有沒有辦法確保我不會選擇同一段落兩次?也許有一個TkInter函數...

否則,人們會檢查列表/字典的內容,並刪除,如果有重複。

+0

如果你的意思是在非常短的時間內雙擊,然後你就可以比較當前'line_beginning'與'previous_line_beginning' – furas

+0

也許你應該使用'<雙鈕釦1>' – furas

回答

0

我會做的是在選定的文本塊上添加一個標籤。然後您可以檢查該標籤的存在。您也可以使用標記來突出顯示代碼,以便用戶知道他們已經點擊了它。

# this step is optional; you don't have to configure a tag 
# before adding it to a range of text 
text.tag_configure("already_selected", background="yellow") 
... 
text.tag_add("already_selected", line_beginning, line_ending) 

要檢查標記是否適用於它們單擊的位置,請使用tag_names方法。例如:

if "already_selected" in text.tag_names("current"): 
    ... 
+0

突出代碼一個好主意!謝謝。我最終做的是爲了避免重複,是爲了傳遞一個集合和一個列表中的「已保存」行。如果新點擊的行不在該集合中,則附加到列表並設置。否則,忽略。 – ShanZhengYang