【问题标题】:Avoid accessing the same location twice/clicking twice, TkInter Text widget避免访问同一位置两次/单击两次,TkInter Text 小部件
【发布时间】:2016-01-13 18:24:27
【问题描述】:

我正在使用 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 函数...

否则,将检查列表/字典内容,如果有重复则删除。

【问题讨论】:

  • 如果您的意思是在很短的时间内双击,那么您可以将当前的line_beginningprevious_line_beginning 进行比较
  • 或者你应该使用&lt;Double-Button-1&gt;

标签: python tkinter


【解决方案1】:

我要做的是在选定的文本块上添加一个标签。然后,您可以检查该标签是否存在。您还可以使用标签突出显示代码,以便用户知道他们已经点击了它。

# 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"):
    ...

【讨论】:

  • 高亮代码是个好主意!谢谢。我最终为避免重复所做的是在集合和列表中传递“已保存”行。如果新单击的行不在集合中,则追加到列表并设置。否则,忽略。
猜你喜欢
  • 2022-08-09
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 2020-04-08
  • 2017-05-23
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
相关资源
最近更新 更多