Reputation: 1975
It's meant to get the iid
of the treeview item when a user clicks on an item and print it out but for some reason identify()
is not receiving the the event.y variable, perhaps?
import tkinter as tk
from tkinter import ttk
class App:
def __init__(self):
self.root = tk.Tk()
self.tree = ttk.Treeview()
self.tree.pack(side="top", fill="both")
self.tree.bind("<<TreeviewSelect>>", self.tree_click_event)
for i in range(10):
self.tree.insert("", "end", text="Item %s" % i)
self.root.mainloop()
def tree_click_event(self, event):
iid = self.tree.identify(event.x,event.y)
print (iid)
if __name__ == "__main__":
app = App()
Upon clicking an item in the treeview the error is:
TypeError: identify() missing 1 required positional argument: 'y'
In response to @TessellatingHeckler 's comment, an edit made to the code based on the link does not produce an error but still will not print out the iid
:
def tree_click_event(self, event):
item = self.tree.identify('item', event.x,event.y)
print (item)
Thank you for the accepted answer from @CommonSense in summary it seems I needed to use self.tree.bind('<1>', self.tree_click_event) instead of treeviewselect for this particular problem, but thanks for providing a second way of doing things aswell
Upvotes: 1
Views: 7453
Reputation: 4482
According to docs x, y
coordinates are
Valid for KeyPress, KeyRelease, ButtonPress, ButtonRelease, Motion, Enter, Leave, Expose, Configure, Gravity, and Reparent events.
So here's a little workaround for your problem with some debug prints (notice <<TreeviewSelect>>
event coordinates!):
try:
import tkinter as tk
import tkinter.ttk as ttk
except ImportError:
import Tkinter as tk
import ttk
class App:
def __init__(self):
self.root = tk.Tk()
self.tree = ttk.Treeview()
self.tree.pack(side="top", fill="both")
self.tree.bind('<<TreeviewSelect>>', self.tree_click_event)
self.tree.bind('<1>', self.on_click)
for i in range(10):
self.tree.insert("", "end", text="Item %s" % i)
self.root.mainloop()
def tree_click_event(self, event):
real_coords = (self.tree.winfo_pointerx() - self.tree.winfo_rootx(),
self.tree.winfo_pointery() - self.tree.winfo_rooty())
item = self.tree.identify('item', *real_coords)
print('********** tree selection event **********')
print('looks like this virtual event doesnt support event coordinates')
print('event.x: %d, event.y: %d' % (event.x, event.y))
print('real.x: %d, real.y: %d' % real_coords)
print('clicked on', self.tree.item(item)['text'])
print('******************************************\n')
def on_click(self, event):
item = self.tree.identify('item', event.x, event.y)
print('********** tree mouse click event **********')
print('clicked on', self.tree.item(item)['text'])
print('event.x: %d, event.y: %d' % (event.x, event.y))
print('******************************************\n')
if __name__ == "__main__":
app = App()
Upvotes: 5