替换 tkinter 列表框中的预定义键绑定函数

Replace predefined key binded functions in tkinter Listbox

我创建了一个列表框,我想要 LeftRight 箭头键上下移动列表框(分别),但 键的默认键绑定功能是像水平滚动一样左右移动列表。

如何替换左右键的功能?

代码可以是这样的吗:

from tkinter import *                                                
window=Tk()                                                          
list_b=Listbox()                                                     
                                                                     
list_b.insert(END,'line 1')                                          
list_b.insert(END,'line 2')                                          
list_b.insert(END,'this is a really really really long line')        
list_b.insert(END,'line 4')                                          
                                                                     
list_b.grid()

list_b.disable_horizontal_scroll() #some method to disable horizontal scroll                                                           
list_b.bind('<Right>',move_down) # has the same effect as the up arrow key                                    
list_b.bind('<Left>',move_up)    # has the same effect as the down arrow key                                  
list_b.focus()                                                       
                                                                     
                                                                     
window.mainloop()

我已经从 尝试了 list_b.bind("<B1-Leave>", lambda event: "break"),但它不会禁用水平滚动。

注意-

我不是要替换 键,我问这个问题是因为它是一个更大的片段,更复杂的代码和给定的代码片段只是一个例子。

您所要做的就是 return 'break' 在您的函数结束时。由于我不知道您的功能,因此我为此目的制作了自己的功能,例如:

def move_down():
    try:
        idx = list_b.curselection()[0]
        list_b.selection_clear(0,'end')
        list_b.selection_set(idx+1)
        list_b.activate(idx+1)
        return 'break'
    except IndexError:
        idx = 0
        list_b.selection_clear(0,'end')
        list_b.selection_set(idx)
        list_b.activate(idx)
        return 'break'

def move_up():
    try:
        idx = list_b.curselection()[0]
        list_b.selection_clear(0,'end')
        list_b.selection_set(idx-1)
        list_b.activate(idx-1)
        return 'break'
    except IndexError:
        idx = list_b.size()
        list_b.selection_clear(0,'end')
        list_b.selection_set(idx-1)
        list_b.activate(idx-1)
        return 'break'
# Binding
list_b.bind('<Right>',lambda event:move_down()) 
list_b.bind('<Left>',lambda event: move_up())    

在绑定到事件的函数中,您需要return字符串“break”以防止默认行为发生。

其次,虽然你当然可以在python中定义move_upmove_down命令来模仿上下键的行为,你也可以直接调用内部tk这些键使用的功能。这就是我将在此处介绍的解决方案:

def move_down(event):
    event.widget.tk.call("tk::ListboxUpDown", event.widget, 1)
    return "break" 

def move_up(event):
    event.widget.tk.call("tk::ListboxUpDown", event.widget, -1)
    return "break"