问题
I'm trying to get my listbox to have the first object highlighted (which happens with self.e1.select_set(0)
. I am now trying to scroll through the listbox highlighting the next item down when hitting the down arrow, or select the next item up by hitting the up arrow. I thought that I could do this with binding but no luck. Any ideas?
def body(self, master):
self.e1 = tk.Listbox(master, selectmode=tk.SINGLE, height = 3, exportselection=0)
self.e1.insert(tk.END, "1")
self.e1.insert(tk.END, "2")
self.e1.grid(row=0, column=1)
self.e1.select_set(0)
self.e1.bind("<Down>", self.OnEntryDown)
self.e1.bind("<Up>", self.OnEntryUp)
def OnEntryDown(self, event):
self.e1.yview_scroll(1, "units")
def OnEntryUp(self, event):
self.e1.yview_scroll(-1, "units")
Thanks!
回答1:
As the name says, yview_scroll
only changes the view, not the selection.
Like you select the first object with select_set(0)
, you can also use select_set
to select the other objects. Keep a reference to which object is selected and use that to select the next or previous object upon button press. Just make sure that the selection does not go below 0 or over the size of the listbox.
Code example:
def body(self, master):
self.e1 = tk.Listbox(master, selectmode=tk.SINGLE, height = 3, exportselection=0)
self.e1.insert(tk.END, "1")
self.e1.insert(tk.END, "2")
self.e1.grid(row=0, column=1)
self.selection = 0
self.e1.select_set(self.selection)
self.e1.bind("<Down>", self.OnEntryDown)
self.e1.bind("<Up>", self.OnEntryUp)
def OnEntryDown(self, event):
if self.selection < self.e1.size()-1:
self.e1.select_clear(self.selection)
self.selection += 1
self.e1.select_set(self.selection)
def OnEntryUp(self, event):
if self.selection > 0:
self.e1.select_clear(self.selection)
self.selection -= 1
self.e1.select_set(self.selection)
来源:https://stackoverflow.com/questions/29484287/tkinter-listbox-that-scrolls-with-arrow-keys