使用一个滚动条滚动浏览多个列表框而不使用类

时间:2017-03-10 10:21:09

标签: python tkinter listbox scrollbar python-3.6

我想使用单个(垂直)滚动条在Tkinter中同时滚动多个列表框(同步)。

问题是Stack Overflow上的所有解决方案似乎都使​​用类将单个滚动条附加到多个列表框。我想在不使用课程的情况下也这样做,如果可能的话,因为我没有任何课程经验。

这是我的代码的简化版本:

from tkinter import *
import tkinter as tk


root = Tk()

##This code will only scroll through 1 listbox.
listbox1 = Listbox(root)
listbox1.grid(row=1, column=2)
listbox2 = Listbox(root)
listbox2.grid(row=1, column=3)
scrollbary = Scrollbar(root, command=listbox1.yview, orient=VERTICAL)
scrollbary.grid(row=1, column=1, sticky="ns")

for i in range(100):
    listbox1.insert("end","item %s" % i)
    listbox2.insert("end","item %s" % i)

1 个答案:

答案 0 :(得分:1)

我调整了http://effbot.org/tkinterbook/listbox.htm中的代码,以便它可以在课堂外使用。

import tkinter as tk

root = tk.Tk()

def yview(*args):
    """ scroll both listboxes together """
    listbox1.yview(*args)
    listbox2.yview(*args)

listbox1 = tk.Listbox(root)
listbox1.grid(row=1, column=2)
listbox2 = tk.Listbox(root)
listbox2.grid(row=1, column=3)
scrollbary = tk.Scrollbar(root, command=yview)
listbox1.config(yscrollcommand=scrollbary.set)
listbox2.config(yscrollcommand=scrollbary.set)
scrollbary.grid(row=1, column=1, sticky="ns")

for i in range(100):
    listbox1.insert("end","item %s" % i)
    listbox2.insert("end","item %s" % i)

root.mainloop()

如果您还想使用鼠标滚轮将它们一起滚动,请参阅此问题的答案:Scrolling multiple Tkinter listboxes together。答案是通过类给出的,但绑定和函数也可以在不使用类的情况下完成。