def nextItem(self):
active = self.skill_list_listbox.get(tk.ACTIVE)
listbox_contents = self.skill_list_listbox.get(0, tk.END)
current_pos = listbox_contents.index(active)
if current_pos + 1 < len(listbox_contents):
new_pos = current_pos + 1
self.skill_list_listbox.activate(new_pos)
self.skill_list_listbox.selection_set(tk.ACTIVE)
从文档中我可以看到,这应该突出显示并激活列表框中的下一个项目。如果我省略了selection_set,我会得到我正在寻找的东西,但是没有指示什么是活跃的。添加它会突出显示一个项目,但是如果您继续单击“下一步”按钮,它只会添加到突出显示,而不是仅突出显示一个项目,创建一长串突出显示的项目,这是我不想要的。我尝试了几种不同的方法,这让我最接近。如果有一个'明确的选择'方法,我想我可以得到我想要的效果,只是选择并突出显示下一个项目,但只有这样做的3个调用对于一项常见任务似乎有点多吗?有什么想法或建议吗?
答案 0 :(得分:1)
以下是我认为您要完成的示例,使用按钮选择列表框中的下一个项目。它的要点在于按钮的回调函数,该函数调用selection_clear
然后调用selection_set
。
更新了示例,希望对其发生的事情更加清楚
import Tkinter
class Application(Tkinter.Frame):
def __init__(self, master):
Tkinter.Frame.__init__(self, master)
self.master.minsize(width=256, height=256)
self.master.config()
self.pack()
self.main_frame = Tkinter.Frame()
self.some_list = [
'One',
'Two',
'Three',
'Four'
]
self.some_listbox = Tkinter.Listbox(self.main_frame)
self.some_listbox.pack(fill='both', expand=True)
self.main_frame.pack(fill='both', expand=True)
# insert our items into the list box
for i, item in enumerate(self.some_list):
self.some_listbox.insert(i, item)
# add a button to select the next item
self.some_button = Tkinter.Button(
self.main_frame, text="Next", command=self.next_selection)
self.some_button.pack(side='top')
# not really necessary, just make things look nice and centered
self.main_frame.place(in_=self.master, anchor='c', relx=.5, rely=.5)
def next_selection(self):
selection_indices = self.some_listbox.curselection()
# default next selection is the beginning
next_selection = 0
# make sure at least one item is selected
if len(selection_indices) > 0:
# Get the last selection, remember they are strings for some reason
# so convert to int
last_selection = int(selection_indices[-1])
# clear current selections
self.some_listbox.selection_clear(selection_indices)
# Make sure we're not at the last item
if last_selection < self.some_listbox.size() - 1:
next_selection = last_selection + 1
self.some_listbox.activate(next_selection)
self.some_listbox.selection_set(next_selection)
root = Tkinter.Tk()
app = Application(root)
app.mainloop()