Tkinter listbox that scrolls with arrow keys

我们两清 提交于 2019-12-24 03:53:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!