使用箭头键滚动的Tkinter列表框 [英] Tkinter listbox that scrolls with arrow keys

查看:63
本文介绍了使用箭头键滚动的Tkinter列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的列表框突出显示第一个对象(self.e1.select_set(0)发生这种情况.现在,我试图滚动列表框以在按下向下箭头时突出显示下一个条目,或者选择下一个条目我以为我可以用绑定但没有运气来做到这一点.有什么想法吗?

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")

谢谢!

推荐答案

顾名思义,yview_scroll仅更改视图,而不更改选择.

As the name says, yview_scroll only changes the view, not the selection.

就像使用select_set(0)选择第一个对象一样,也可以使用select_set选择其他对象.保留选择哪个对象的引用,并在按下按钮时使用它来选择下一个或上一个对象.只需确保所选内容不低于0或超过列表框的大小即可.

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.

代码示例:

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)

这篇关于使用箭头键滚动的Tkinter列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆