Pressing tab with tkinter Listboxes moves the "Active" underscore but not the cursor

时间:2016-12-28 22:24:10

标签: python tkinter tabs listbox

l1=Listbox()
l1.pack(side=LEFT)
l1.insert(END, *xrange(1,4))

l2=Listbox()
l2.pack(side=RIGHT)
l2.insert(END, *'abc')

When I press tab, the underscore jumps to the other Listbox, but the cursor only joins in when I start using the up/down arrows. Is it possible to make it hop along together with the underscore, on pressing tab?

Edit: This is done by binding the Tab key to invoke the select_set() method on the active item:

l1.bind('<Tab>', lambda e: l2.select_set(l2.index(ACTIVE)))
l2.bind('<Tab>', lambda e: l1.select_set(l1.index(ACTIVE)))
  • l.index(ACTIVE) returns the index of the active item, which is the one with the underscore after Tab is pressed.

  • It is then set to be "selected" using l.select_set(), which moves the cursor to it as well.

  • the "e" after lambda is required since any function called from a tkinter bind is implicitly given an event object, though it isn't used in any way here.

Hope this comes handy.

1 个答案:

答案 0 :(得分:0)

下划线和光标表示列表框项目的不同属性 -

  • 下划线标记,这是默认的activestyle属性 列表框,显示活动项目。

  • 光标用于(a)所选项目。

默认情况下,Tab键交替显示&#34;活动&#34;在此上下文中的状态,因此它不会影响游标。

要更改光标位置,我们还需要将活动项目设置为(a)所选项目。我已经通过将Tab键绑定到执行此额外操作的lambda函数来完成此操作:

l1.bind('<Tab>', lambda e: l2.select_set(l2.index(ACTIVE)))
l2.bind('<Tab>', lambda e: l1.select_set(l1.index(ACTIVE)))

活动索引作为相应select_set()的参数给出,然后将光标移动到下划线项上。

注意:我认为对于更一般的情况,应使用事件e来获取活动项,而不是直接引用列表框。但是,这似乎适用于2个列表框。