我的python应用程序中有几个tkinter组合框,其默认的tkinter行为是'向上'箭头不做任何事情,'向下'箭头显示整个值列表,然后可以使用箭头键反转。
但是,我想在不弹出列表的情况下用箭头键"滚动"组合框(即向下箭头直接切换到下一个元素,向上箭头直接切换到上一个元素)。
组合框MWE:
import tkinter as tk
import tkinter.ttk as ttk
app = tk.Tk()
combo = ttk.Combobox(app, values = [f"item {i}" for i in range(20)])
combo.grid()
(如何)我可以实现这个期望的行为?我是否必须抓住关键事件,或者我是否错过了某些设定?
这是一个解决方案,应该同时适用于Up
和Down
import tkinter as tk
import tkinter.ttk as ttk
def select_next(event):
selection = combo.current() # get the current selection
last = len(combo['values']) - 1 # index of last item
key = event.keysym # get the key that was pressed
if key == 'Up':
try:
combo.current(selection - 1) # set the combobox to the previous item
except tk.TclError: # end of list reached
combo.current(last) # wrap around to last item
elif key == 'Down':
try:
combo.current(selection + 1) # set the combobox to the next item
except tk.TclError: # end of list reached
combo.current(0) # wrap around to first item
return 'break' # tell tk to dispose of this event and don't show the menu!
app = tk.Tk()
combo = ttk.Combobox(app, values = [f"item {i}" for i in range(20)])
combo.grid()
combo.current(0) # select the first item by default
combo.bind('<Up>', select_next) # up arrow
combo.bind('<Down>', select_next) # down arrow