Python Tkinter:更新滚动列表框 - 漫游滚动位置

时间:2016-03-18 14:05:06

标签: python tkinter listbox

我想显示一个在可滚动的GUI窗口中定期更新的字符串项的长列表。 我喜欢使用Tkinter免费使用电池,并遇到了一些问题:

  • Tkinter Listbox无法更新项目,您必须删除并重新打印它们。
  • 重新插入使滚动条向上移动
  • 总Tkinter初学者

我解决了这个问题,并将分享解决方案作为这个问题的答案。 如果你知道更好的方法,请发表改进的答案。

1 个答案:

答案 0 :(得分:0)

诀窍是,要保存列表框的yview,修改内容,然后返回到该位置。 所以,这是我使用Tkinter的解决方案:

from Tkinter import * # I do not like wild imports, but everyone seems to do it

root = Tk()

scrollbar = Scrollbar(root, orient=VERTICAL) # yes, do this first...
listb = Listbox(root, yscrollcommand=scrollbar.set) # ...because you need it here
scrollbar.config(command=listb.yview)
scrollbar.pack(side=RIGHT, fill=Y)
listb.pack(fill=BOTH, expand=YES) # convince the listbox to resize

item_list = range(400)

for item in item_list:
    listb.insert(item)

exponent = 0
def update_list():
    global exponent
    vw = listb.yview() # Save the current position(percentage) of the top left corner
    for i in item_list:
        listb.delete(i)
        listb.insert(i, i * 10**exponent)
    listb.yview_moveto(vw[0]) # go back to that position
    exponent += 1
    root.after(1000, update_list)

root.after(1000, update_list)
root.mainloop()
相关问题