Tkinter有三个几何管理器:
pack,
grid和
place.
包装和电网通常被推荐到位.
您可以使用grid manager’s行和列选项
将“滚动条”放置在“文本”小部件旁边.
将Scrollbar小部件的命令选项设置为Text的yview方法.
scrollb = tki.Scrollbar(..., command=txt.yview)
将Text widget的yscrollcommand选项设置为Scrollbar的set方法.
txt['yscrollcommand'] = scrollb.set
这是一个工作示例:
import Tkinter as tki # Tkinter -> tkinter in Python3
class App(object):
def __init__(self):
self.root = tki.Tk()
# create a Frame for the Text and Scrollbar
txt_frm = tki.Frame(self.root, width=600, height=600)
txt_frm.pack(fill="both", expand=True)
# ensure a consistent GUI size
txt_frm.grid_propagate(False)
# implement stretchability
txt_frm.grid_rowconfigure(0, weight=1)
txt_frm.grid_columnconfigure(0, weight=1)
# create a Text widget
self.txt = tki.Text(txt_frm, borderwidth=3, relief="sunken")
self.txt.config(font=("consolas", 12), undo=True, wrap='word')
self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)
# create a Scrollbar and associate it with txt
scrollb = tki.Scrollbar(txt_frm, command=self.txt.yview)
scrollb.grid(row=0, column=1, sticky='nsew')
self.txt['yscrollcommand'] = scrollb.set
app = App()
app.root.mainloop()
解决您的滚动条小的部分是sticky =’nsew’,
您可以阅读→here或here.
有助于您现在学习的东西是,不同的Tkinter小部件可以在同一程序中使用不同的几何管理器,只要它们不共享相同的父代.
还值得一提的是有ScrolledText模块(在Python3中改名为tkinter.scrolledtext).
它包含一个类,也称为ScrolledText,它是一个复合的小部件(Text& Scrollbar).
# Python 2.7
import Tkinter as tki
from ScrolledText import ScrolledText
class App(object):
def __init__(self):
self.root = tki.Tk()
# create a Text widget with a Scrollbar attached
self.txt = ScrolledText(self.root, undo=True)
self.txt['font'] = ('consolas', '12')
self.txt.pack(expand=True, fill='both')
app = App()
app.root.mainloop()