0
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 次调用只是为了做这件事对于一项常见任务来说似乎有点多?有什么想法或建议吗?

4

1 回答 1

1

下面是我认为您正在尝试完成的示例,使用按钮选择列表框中的下一个项目。它的要点在于按钮的回调函数,它调用selection_clearthen 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()
于 2013-10-30T22:54:28.900 回答