簡體   English   中英

獲取線鼠標在 tkinter 文本上

[英]Getting line mouse is on tkinter text

我正在嘗試為 tkinter Text 小部件制作一個側邊欄,該小部件在鼠標懸停的行旁邊顯示一個紅點。 目前它被配置為轉到選定的行,但如果它跟蹤鼠標會更好。 我知道如何使用root.winfo_pointery()跟蹤鼠標的 y 位置,但不知道如何獲得相應的行。 如果它超出文本小部件的 y 區域或沒有線條,我也不希望它顯示任何內容。 如何交叉比較指針的 y 值與文本行?

當前代碼:

from tkinter import *
class BreakpointBar(Canvas):
    def __init__(self, *args, **kwargs):
        #Initializes the canvas
        Canvas.__init__(self, *args, **kwargs, highlightthickness=0)
        self.textwidget = None
        self.ovals = []

    def attach(self, text_widget):
        #Attaches the canvas to the text widget
        self.textwidget = text_widget

    def redraw(self, *args):
        #Redraws the canvas
        """redraw line numbers"""
        # try:
        self.delete("all")
        self.unbind_all("<Enter>")
        self.unbind_all("<Leave>")
        self.ovals = []
        index = self.textwidget.index("insert")
        index_linenum = str(index).split(".")[0]


        i = self.textwidget.index("@0,0")
        print(self.winfo_pointerx())
        print(self.winfo_pointery())
        while True :
            dline= self.textwidget.dlineinfo(i)
            if dline is None: break
            y = dline[1]
            linenum = str(i).split(".")[0]
            if linenum == index_linenum:
                oval = self.create_oval(5, y, 15, y+10, fill="red", outline="red")
                self.tag_bind(oval, "<Enter>", lambda event: self.on_enter(event, oval))
                self.tag_bind(oval, "<Leave>", lambda event: self.on_exit(event, oval))
                self.tag_bind(oval, "<Button-1>", lambda event: self.on_press(event, oval))
                self.ovals.append(oval)
            i = self.textwidget.index("%s+1line" % i)
        # except:
        #     pass

    def on_enter(self, event, oval):
        self.itemconfig(oval, fill="dark red", outline="dark red")


    def on_exit(self, event, oval):
        self.itemconfig(oval, fill="red", outline="red")

    def on_press(self, event, oval):
        index_linenum = int(str(self.textwidget.index("insert")).split(".")[0])
        self.textwidget.insert("{}.end".format(index_linenum), "\nbreakpoint\n")
        self.textwidget.mark_set("insert", "{}.0".format(index_linenum+2))
        self.textwidget.see("insert")
root = Tk()
frame = Frame(root)
frame.pack(expand=True, fill=BOTH)
text=Text(frame)
text.pack(side=RIGHT, fill=BOTH, expand=True)
bb = BreakpointBar(frame, width=20)
bb.attach(text)
bb.pack(side=LEFT, fill=Y)
root.bind("<Button-1>", bb.redraw)
root.bind("<KeyRelease-Return>", bb.redraw)
root.mainloop()

您可以使用@x,y格式通過 x,y 坐標獲取離鼠標最近的字符的索引。

例如,如果您有一個綁定到<Motion>事件的函數,您可以通過執行以下操作來獲取光標下的索引:

def track_mouse(event):
    index = event.widget.index(f"@{event.x},{event.y}")
    ...

在上面的示例中, index將采用line.character格式的字符串的規范形式。

請務必注意,您必須提供相對於文本小部件本身的左上角的坐標,而不是相對於窗口或整個顯示的坐標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM