I want to implement a Text Drag-n-Drop feature in my text editor. So far I get the text that I've dropped by event.data
, and the position where I dropped the text by event.x_root
and event.y_root
. Please help me out with setting insert cursor of tk.Text by dropped position.
I'm using tkdnd2.8 as an extension and TkinterDnD2 as a wrapper.
Here is my code:
import tkinter as tk
import TkinterDnD2.TkinterDnD as tkdnd
def drop(event):
print("x: %d"%event.x_root, "y: %d"%event.y_root, "text:'%s'"%event.data)
root = tkdnd.Tk()
text = tk.Text(root, width=50, height=10)
text.pack()
text.drop_target_register("DND_Text")
text.dnd_bind('<<Drop:DND_Text>>', drop)
root.mainloop()
If I drag a piece of text "SomeText" onto my text widget, here is the console output:
x: 60 y: 306 text:'SomeText'
Now I'm struggle on how to convert the position from pixel scale to character scale so that I can set it to text widget's INSERT cursor and insert text into my text widget.
Or, can I just emit a "<Button-1>"
and "<ButtonRelease-1>"
event at certain position? If so, how can I do that?
You can specify an index by a coordinate using the format @x,y
. From the canonical tcl/tk documentation
@x,y Indicates the character that covers the pixel whose x and y coordinates within the text's window are x and y.
You should use the event x and y for the widget, not for the root. This is a standard, documented feature of the Text
widget. You can use an f-string to create the index like so:
index = f"@{event.x},{event.y}"
The above will yield something like "@100,200".
You can use that index in any method call that takes an index. To convert that to a numerical index you can pass it to the index
method. For example:
numerical_index = text.index(index)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.