返回在 tkinter 列表框中单击的项目的索引
Returning the index of an item clicked in a tkinter Listbox
我正在尝试让 tkinter return 在列表框中单击的项目的索引。这是我的代码。
def fileSelection(self):
selection = listbox.curselection
print(selection)
listbox.bind("<Button-1>", fileSelection)
现在它打印
bound method Listbox.curselection of tkinter.Listbox object at 0x00320E30
无论点击什么项目。如果我更改代码以包含这样的按钮:
button = Button(text=u"test", command=OnButtonClick)
def OnButtonClick():
selection = listbox.curselection()
print(selection)
和 select 列表框项,然后单击按钮,它将按预期打印 selected 项的索引,但这是我不想要的额外步骤。
def fileSelection(self):
selection = listbox.curselection
print(selection)
你好像忘记了括号。
def fileSelection(self):
selection = listbox.curselection()
print(selection)
根据 effbot.org,轮询小部件允许您进行点击更新。
self.current = None
self.listbox = Listbox(self)
self.listbox.pack()
self.poll()
def poll(self):
now = self.listbox.curselection()
if now != self.current:
self.list_has_changed(now)
self.current = now
self.after(250, self.poll)
def list_has_changed(self, selection):
print "selection is", selection
我正在尝试让 tkinter return 在列表框中单击的项目的索引。这是我的代码。
def fileSelection(self):
selection = listbox.curselection
print(selection)
listbox.bind("<Button-1>", fileSelection)
现在它打印
bound method Listbox.curselection of tkinter.Listbox object at 0x00320E30
无论点击什么项目。如果我更改代码以包含这样的按钮:
button = Button(text=u"test", command=OnButtonClick)
def OnButtonClick():
selection = listbox.curselection()
print(selection)
和 select 列表框项,然后单击按钮,它将按预期打印 selected 项的索引,但这是我不想要的额外步骤。
def fileSelection(self):
selection = listbox.curselection
print(selection)
你好像忘记了括号。
def fileSelection(self):
selection = listbox.curselection()
print(selection)
根据 effbot.org,轮询小部件允许您进行点击更新。
self.current = None
self.listbox = Listbox(self)
self.listbox.pack()
self.poll()
def poll(self):
now = self.listbox.curselection()
if now != self.current:
self.list_has_changed(now)
self.current = now
self.after(250, self.poll)
def list_has_changed(self, selection):
print "selection is", selection