问题描述
限时送ChatGPT账号..我创建了一个列表框,我希望 Left 和 Right
箭头键(分别)上下移动列表框,但是→和←键的默认键绑定功能是像水平滚动一样左右移动列表.
I've created a listbox and I want the Left and Right
arrow keys to move up and down the listbox (respectively) but the default key binded functions of → and ← keys are to move the list left and right like a horizontal scroll.
如何替换左右键的功能?
How do I replace the function of the left and right keys?
代码看起来像这样:
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()
我已经从 如何在 Tkinter 列表框中禁用水平滚动?(Python 3) 但它不会禁用水平滚动.
I've already tried list_b.bind("<B1-Leave>", lambda event: "break")
from How can I disable horizontal scrolling in a Tkinter listbox? (Python 3) but it does not disable horizontal scrolling.
注意-
我不是要替换 ↑ 和 ↓ 键,我问了这个问题,因为它是更大、更复杂代码和给定代码段的一部分代码只是一个例子.
I'm not trying to replace the ↑ and ↓ keys, I asked this question as it is a segment of a larger, more complex code and the given snippet of the code is merely an example.
推荐答案
您所要做的就是在函数的末尾return 'break'
.由于我不知道您的功能,因此我为此目的制作了自己的功能,例如:
All you have to do is return 'break'
at the end of your function. Since I dont know your functions, I made my own for this purpose, like:
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())
这篇关于替换 tkinter 列表框中的预定义键绑定函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论