Tkinterには、 pack、grid、placeの3つのジオメトリマネージャーがあります。
パックとグリッドは通常、場所よりも推奨されます。
グリッドマネージャーの 行と列のオプションを使用して、テキストウィジェット の横にスクロールバー
を配置できます。
スクロールバーウィジェットのコマンドオプションをテキストのyviewメソッド に設定します。
scrollb = tkinter.Scrollbar(..., command=txt.yview)
テキストウィジェットのyscrollcommandオプションをスクロールバーのsetメソッドに設定します。
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'
、 →ここで
読むことができます。
今すぐ学ぶのに役立つことは、異なるTkinterウィジェットは、同じ親を共有しない限り、同じプログラム内で異なるジオメトリマネージャーを使用できるということです。
tkinter.scrolledtextモジュールには、複合ウィジェット(Text&Scrollbar)である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()
これが実装される方法は一見の価値があります。