Tkinter有三个几何管理器: pack, grid, and place.
通常建议使用 Pack 和 grid,而不是 place。
您可以使用网格经理的 row and column options
定位滚动条旁边的Text小部件。
Set the 滚动条小部件的command文本的选项yview方法。
scrollb = tkinter.Scrollbar(..., command=txt.yview)
Set the Text小部件的yscroll命令滚动条的选项set method.
txt['yscrollcommand'] = scrollb.set
这是一个使用的工作示例ttk:
import tkinter
import tkinter.ttk as ttk
class TextScrollCombo(ttk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# ensure a consistent GUI size
self.grid_propagate(False)
# implement stretchability
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
# create a Text widget
self.txt = tkinter.Text(self)
self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)
# create a Scrollbar and associate it with txt
scrollb = ttk.Scrollbar(self, command=self.txt.yview)
scrollb.grid(row=0, column=1, sticky='nsew')
self.txt['yscrollcommand'] = scrollb.set
main_window = tkinter.Tk()
combo = TextScrollCombo(main_window)
combo.pack(fill="both", expand=True)
combo.config(width=600, height=600)
combo.txt.config(font=("consolas", 12), undo=True, wrap='word')
combo.txt.config(borderwidth=3, relief="sunken")
style = ttk.Style()
style.theme_use('clam')
main_window.mainloop()
将解决您的问题的部分滚动条小是sticky='nsew'
,
您可以阅读→here.
对你现在学习有帮助的东西是不同的Tkinter小部件可以使用不同的几何管理器在同一程序内只要他们不属于同一个父母.
The tkinter.scrolledtext模块包含一个名为的类滚动文本这是一个复合小部件(文本和滚动条)。
import tkinter
import tkinter.scrolledtext as scrolledtext
main_window = tkinter.Tk()
txt = scrolledtext.ScrolledText(main_window, undo=True)
txt['font'] = ('consolas', '12')
txt.pack(expand=True, fill='both')
main_window.mainloop()
这是这样的方式实施的值得一看。