如何在Tkinter列表框中插入时添加自动滚动? [英] How to add Autoscroll on insert in Tkinter Listbox?

查看:122
本文介绍了如何在Tkinter列表框中插入时添加自动滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个列表框(带有滚动条)进行记录:

I'm using a listbox (with scrollbar) for logging:

self.listbox_log = Tkinter.Listbox(root, height = 5, width = 0,)
self.scrollbar_log = Tkinter.Scrollbar(root,)

self.listbox_log.configure(yscrollcommand = self.scrollbar_log.set)
self.scrollbar_log.configure(command = self.listbox_log.yview)

现在,当我这样做时:

Now, when I do:

self.listbox_log.insert(END,str)

我希望选择插入的元素.我试过了:

I want the inserted element to be selected. I've tried:

self.listbox_log.selection_anchor(END)

但这不起作用...请提出解决方案...

but that doesn't work... Please suggest a solution...

推荐答案

AFAIK ScrollBar小部件没有自动滚动功能,但是可以通过在之后调用listBoxyview()方法来轻松实现您插入一个新项目.如果需要选择新项目,则也可以使用listboxselect_set方法手动进行.

AFAIK the ScrollBar widget doesn't have an auto-scroll feature, but it can be easily implemented by calling the listBox's yview() method after you insert a new item. If you need the new item to be selected then you can do that manually too using the listbox's select_set method.

from Tkinter import *

class AutoScrollListBox_demo:
    def __init__(self, master):
        frame = Frame(master, width=500, height=400, bd=1)
        frame.pack()

        self.listbox_log = Listbox(frame, height=4)
        self.scrollbar_log = Scrollbar(frame) 

        self.scrollbar_log.pack(side=RIGHT, fill=Y)
        self.listbox_log.pack(side=LEFT,fill=Y) 

        self.listbox_log.configure(yscrollcommand = self.scrollbar_log.set)
        self.scrollbar_log.configure(command = self.listbox_log.yview)

        b = Button(text="Add", command=self.onAdd)
        b.pack()

        #Just to show unique items in the list
        self.item_num = 0

    def onAdd(self):
        self.listbox_log.insert(END, "test %s" %(str(self.item_num)))       #Insert a new item at the end of the list

        self.listbox_log.select_clear(self.listbox_log.size() - 2)   #Clear the current selected item     
        self.listbox_log.select_set(END)                             #Select the new item
        self.listbox_log.yview(END)                                  #Set the scrollbar to the end of the listbox

        self.item_num += 1


root = Tk()
all = AutoScrollListBox_demo(root)
root.title('AutoScroll ListBox Demo')
root.mainloop()

这篇关于如何在Tkinter列表框中插入时添加自动滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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