使用Tkinter检测列表框中的自动项目选择

时间:2016-09-08 12:50:27

标签: python events tkinter listbox

我的意思是,对于按钮你可以这样写:

def addItem():
    pass
addbtn = Button(mainFrame, text = "Add Item", command = addItem)

我如何为列表框做同样的事情?比如这个例如:

def on_selection():
    pass
list = Listbox(mainFrame, selectmode = SINGLE, command = on_selection) # This doesn't work.

关键是当我使用mainFrame.bind("<<ListboxSelect>>", on_selection) 自动选择项目时绑定list.selection_set(selection) 不起作用。

换句话说,在调用list.selection_set(...)时自动触发on_selection()函数,而不会覆盖Listbox类或selection_set函数。目标是写一行而不是

list.selection_set(selct)
on_selection()

每一次。

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:0)

import tkinter as tk

root = tk.Tk()

def on_selection(event):
  print(dir(event))

def some_nonevent():
  print(str(2 + 2))

listbox = tk.Listbox(root, selectmode=tk.SINGLE, activestyle='none')
for name in ['john', 'tim', 'sam', 'jill', 'sandra']:
  listbox.insert(tk.END, name)

listbox.bind('<<ListboxSelect>>', on_selection)

listbox.selection_set(3)

listbox.grid()

with open('myfile.py') as f:
  contents = f.read()
  if '\nlistbox.selection_set(2)\n' in contents:
    listbox.event_generate('<<ListboxSelect>>')
    some_nonevent()
  else:
    print('do nothing')

root.mainloop()