当用户点击某个项目并将其打印出来但是由于某种原因iid
没有收到该event.y变量时,它意味着获取该树视图项的identify()
,也许?
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()
单击树视图中的项目时,错误为:
TypeError: identify() missing 1 required positional argument: 'y'
在回复@TessellatingHeckler的评论时,根据链接对代码进行的编辑不会产生错误,但仍然无法打印出iid
:
def tree_click_event(self, event):
item = self.tree.identify('item', event.x,event.y)
print (item)
感谢@CommonSense接受的答案摘要似乎我需要使用self.tree.bind(&#39;&lt; 1&gt;&#39;,self.tree_click_event)而不是treeviewselect来解决这个特殊问题,但感谢提供第二种做事方式
答案 0 :(得分:1)
根据docs x, y
坐标是
适用于KeyPress,KeyRelease,ButtonPress,ButtonRelease,Motion,Enter,Leave,Expose,Configure,Gravity和Reparent事件。
所以这里有一些解决方法针对您的问题进行一些调试打印(注意<<TreeviewSelect>>
事件坐标!):
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()