python tkinter scrollbar and text widget issues

2020-07-30 02:30发布

问题:

I'm trying to get two text boxes that each have scrollbars. When I try this however:

from Tkinter import *

root = Tk()

s_start = Scrollbar(root)
t_start = Text(root, width=50, height=10)

t_start.focus_set()

s_start.pack(side=RIGHT, fill=Y)
t_start.pack(side=LEFT, fill=Y)

s_start.config(command=t_start.yview)
t_start.config(yscrollcommand=s_start.set)

s_end = Scrollbar(root)
t_end = Text(root, width=50, height=10)

t_end.focus_set()

s_end.pack(side=RIGHT, fill=Y)
t_end.pack(side=LEFT, fill=Y)

s_end.config(command=t_end.yview)
t_end.config(yscrollcommand=s_end.set)

root.mainloop()

This happens:

In case this isn't clear, those are two separate text boxes, with the right textbox functionally bound to the inner scroll bar, and the left textbox functionally bound to the outer scrollbar.

回答1:

The trick is to use Frames and add the Scrollbars to the Frames instead of to Root.

from Tkinter import *

root = Tk()

left = Frame(root)
right = Frame(root)

t_start = Text(left, width=20)
t_start.pack(side=LEFT, fill=Y)
s_start = Scrollbar(left)
s_start.pack(side=RIGHT, fill=Y)
s_start.config(command=t_start.yview)
t_start.config(yscrollcommand=s_start.set)

t_end = Text(right, width=20)
t_end.pack(side=LEFT, fill=Y)
s_end = Scrollbar(right)
s_end.pack(side=RIGHT, fill=Y)
s_end.config(command=t_end.yview)
t_end.config(yscrollcommand=s_end.set)

left.pack(side=LEFT, fill=Y)
right.pack(side=RIGHT, fill=Y)

root.geometry("500x200")
root.mainloop()