python - 返回在 tkinter 列表框中单击的项目的索引

标签 python tkinter listbox selection

我试图让 tkinter 返回在列表框中单击的项目的索引。这是我的代码。

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)

并选择列表框项目,然后单击按钮,它将按预期打印所选项目的索引,但这是我不想要的额外步骤。

最佳答案

def fileSelection(self):
    selection = listbox.curselection
    print(selection)

看起来你忘记了括号。

def fileSelection(self):
    selection = listbox.curselection()
    print(selection)

关于python - 返回在 tkinter 列表框中单击的项目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31012566/

相关文章:

python - 为什么我的按钮的命令在我创建按钮时立即执行,而不是在我单击它时执行?

c# - 一般拖放 ListBoxItems

python - Matlab 和 Numpy+Python FFT2 之间的差异?

python - 使用非 ascii verbose_name 的 Django 模型时 manage.py syncdb 错误

python - 更改模式顺序时正则表达式搜索不起作用

python - 有没有办法在 Python 高级字符串格式 "foo {}".format(bar) 中添加条件字符串?

python - 使用按钮事件 tkinter 在 Canvas 中创建图像

python - 使用 SetParent win32gui 函数将 ffplay 窗口嵌入到 tkinter 框架中

wpf - 使 ListBox 填充父容器的宽度

c# - 如何使用 C# 中的字符串从具有数据源集的列表框中删除项目