Reputation: 37
i'm trying to display an Entry at [x,y (coordinate of a Double mouse click) .
import tkinter
from tkinter import *
from tkinter import ttk
def Click(event):
PX = event.x
PY = event.y
En = Entry(Windo)
En.place(x=PX ,y=PY)
Windo = Tk()
EList = ["A","B","C","D"]
Windo.bind("<Double-Button-1>" ,Click)
tree = ttk.Treeview(Windo)
tree.pack()
Tree = ttk.Treeview(Windo)
Tree.pack()
for element in EList:
Tree.insert('' ,'end' ,text=element)
So with the above code i'm able to actually do i wanted (an Entry popup at X,Y) but when i double click on a row in my [Tree] the Entry doesn't popup at the right position ... But when i click on a row in [tree] the Entry popup at the right position...
so i tried something different (bind to the tree) but same thing happened :
Tree.bind("<Double-Button-1>" ,Click)
Upvotes: 2
Views: 135
Reputation: 385900
Event coordinates are relative to the widget that got the event.
When you click in the upper-left corner of the bottom widget, the x,y will be 0,0 because that is where you clicked relative to the widget. When you use place
, the coordinates are also relative to the widget into which you are placing the widget.
In your case, let's say you click on 20,20 in the bottom window. That's what event.x
and event.y
report. However, you're setting the parent of the new entry widget to be Windo
, so placing a widget at 20,20 will go to coordinate 20,20 of Windo
and not 20,20 of the widget you clicked in. That is why it appears in the top portion of the window.
There are a couple ways to fix it, depending on what you actually want to do. For example, if you're trying to create a widget under the mouse, a simple solution is to make the widget a child of the widget you clicked on rather than always making it the root window.
For example:
def Click(event):
...
En = Entry(event.widget)
...
This has the problem if you click on an edge of a widget, the entry widget might be obscured since it can't go beyond the edges of its parent.
If you want the entry to always be a widget of the root (and thus, not obscured by any other widgets), you need to translate the event coordinates to be relative to the root rather than relative to the widget:
def Click(event):
PX = event.widget.winfo_x() + event.x
PY = event.widget.winfo_y() + event.y
En = Entry(Windo)
En.place(x=PX ,y=PY)
Upvotes: 2