【问题标题】:Click event to highlight text单击事件以突出显示文本
【发布时间】:2019-09-03 21:36:13
【问题描述】:

如何创建允许用户通过左键单击和拖动来突出显示文本的事件?

我是编程新手。到目前为止,我已经尝试通过单击一个单词来突出显示该单词来简化它,但我认为我的 tag_bind() 函数存在问题。

import wx
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import tkinter as tk
from tkinter import *
root = Tk()

def text_click_callback(event):
    # an event to highlight a line when single click is done
    line_no = event.widget.index("@%s,%s linestart" % (event.x, 
event.y))
    #print(line_no)
    line_end = event.widget.index("%s lineend" % line_no)
    event.widget.tag_remove("highlight", 1.0, "end")
    event.widget.tag_add("highlight", line_no, line_end)
    event.widget.tag_configure("highlight", background="yellow")

File_object = open(r"Recall Tests.txt", "r")


m = PanedWindow(root)
m.pack(fill=BOTH, expand=1)


text1 = Text(m, height=90, width=90)
m.add(text1)
fileList = File_object.readlines()
text1.insert(INSERT, ''.join(fileList))
text1.config(state=DISABLED)

text1.tag_bind(text1, "highlight", text_click_callback)



text2 = Text(m, height=90, width=90, highlightcolor="black")
m.add(text2)
Label_1 = tk.Label(text2, text="NOTES",fg="red", font="Ariel 16 
underline").grid(row=4, column=0)
Label_2 = tk.Label(text2, text="PID:").grid(row=1)
e1 = tk.Entry(text2, width=90)
e1.grid(row=1, column=1)


root.mainloop()

这会在左侧打开一个文本文件,在右侧打开一个文本框。我希望用户能够通过左键单击并拖动鼠标来突出显示文本文件上显示的句子。我试图让点击功能首先工作,但是当文件打开时,左键点击什么都不做。

【问题讨论】:

    标签: tkinter highlight python-3.7


    【解决方案1】:

    左键不起作用的原因是你绑定了一个标签,程序启动时,没有那个标签。

    如果您希望点击在文本中的任何位置起作用,请使用bind 而不是tag_bind

    text1.bind("<B1>", text_click_callback)
    

    如果您希望在用户拖动鼠标时突出显示,您需要绑定到&lt;B1-Motion&gt;

    text1.bind("<B1>", text_click_callback)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 2015-03-14
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多