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

问题描述 投票:0回答:2

我想在 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)
python tkinter listbox scrollbar python-3.6
2个回答
2
投票

我改编了 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()

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


0
投票

下面的清单是 John K. Ousterhout 的书

Tcl and Tk Toolkit
(2009),第
18.9.2 Synchronized Scrolling of Multiple Widgets
章中的 Tcl 代码示例的 Python 实现。

import tkinter as tk
from tkinter import ttk

# Scrolling multiple listboxes together

root = tk.Tk()
lb1 = tk.Listbox(root)
lb2 = tk.Listbox(root)
scrollbar = ttk.Scrollbar(root)


def lb1_yscrollcommand(*args):
    scrollbar.set(*args)
    lb2.yview("moveto", args[0])


def lb2_yscrollcommand(*args):
    lb1.yview("moveto", args[0])


def scrollbar_command(*args):
    lb1.yview(*args)
    lb2.yview(*args)


lb1.configure(yscrollcommand=lb1_yscrollcommand)
lb2.configure(yscrollcommand=lb2_yscrollcommand)
scrollbar.configure(command=scrollbar_command)
lb1.pack(side="left", fill="both", expand=True)
lb2.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

# Generate some dummy data
for i in range(100):
    lb1.insert("end", f"item lb1 {i}")
    lb2.insert("end", f"item lb2 {i}")

root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.