TurboC
TurboC

Reputation: 908

Tkinter - How can I sync two Scrollbar's with two Text widget's to mirrow each others view?

I need to sync two scrolled bars. both of them manage a different text widget and when I scroll in the first one, I want to see the same behaviour in the second one. I don't want to use a single scrolled bar, both of them must to be syncronized. how can I rech my goal? below a simple example code (here the scrolled bars are not syncronized). help me to fix it. thanks for your support.

import tkinter as tk
root = tk.Tk()

file1data = ("ciao\n"*100)

S1 = tk.Scrollbar(root)
S1.grid(row=0, column=1,sticky=tk.N + tk.S + tk.E + tk.W)
template1 = tk.Text(root, height=25, width=50,wrap=tk.NONE, yscrollcommand=S1.set)
template1.grid(row=0, column=0)
template1.insert(tk.END, file1data)
S1.config(command=template1.yview)

S2 = tk.Scrollbar(root)
S2.grid(row=0, column=3,sticky=tk.N + tk.S + tk.E + tk.W)
template2 = tk.Text(root, height=25, width=50, wrap=tk.NONE, yscrollcommand=S2.set)
template2.grid(row=0, column=2)
template2.insert(tk.END, file1data)
S2.config(command=template2.yview)

tk.mainloop()

Upvotes: 2

Views: 247

Answers (1)

Thingamabobs
Thingamabobs

Reputation: 8037

You can achieve this by writing a function:

def sync_scroll(*args):
    template1.yview(*args)
    template2.yview(*args)

and setting the scrollbars to this command:

S1.config(command=sync_scroll)
S2.config(command=sync_scroll)

The sync_scroll will be triggered by each of the scrollbars with the already calculated position and mirror it's position with the moveto command or the scroll command. Same applies to xview. Basically all they do is to calculate the relative position or parse the appropriated arguments and use the moveto or scroll command to configure the view. If you decide to have a binding to the mousewheel you can use the same mechanic to achieve this in the other direction.

EDIT:

Thanks to @acw1668 for pointing out that the function didn't cover the arrow buttons before and for the shortening version of this code.

Upvotes: 1

Related Questions