すべてをフレームに入れずに、ウィンドウ全体にスクロールバーを追加する方法はありますか? 私は .grid ですべてをセットアップしましたが、すべてをフレームで囲むという考えは好きではありません。
root = Tk()
root.maxsize(900,600)
circus()#calls the function to set up everything
root.mainloop()
素晴らしいeffbot docsから:
Tkinter では、スクロールバーは独立したウィジェットであり、標準のスクロールバー インターフェイスをサポートする任意のウィジェットにアタッチできます。このようなウィジェットには次のものがあります。
- リストボックス ウィジェット。
- テキスト ウィジェット。
- キャンバス ウィジェット
- エントリ ウィジェット
そのため、Frame でスクロールバーを直接使用することはできません。スクロールバー インターフェイスをサポートする独自の Frame サブクラスを作成できる場合があります。
上記の 4 つのウィジェットのうち、1 つだけがその中に他のウィジェットを許可します: Canvas. Canvas を使用してスクロール可能なコンテンツを作成できますが、Canvas 内にウィジェットを配置すると、パックやグリッドは使用されず、明示的なピクセル位置が使用されます (つまり、Canvas でのペイント)。
スクロールバーをルートに設定できる場合があります。
scrollderoot = tkinter.Scrollbar(orient="vertical", command=root.yview)
scrollderoot.grid(column=5, row=0, sticky='ns', in_=root) #instead of number 5, set the column as the expected one for the scrollbar. Sticky ns will might be neccesary.
root.configure(yscrollcommand=scrollderoot.set)
正直なところ、私はこれを試していませんでしたが、「すべき」です。幸運を。
.place
メソッドを使用してウィンドウ全体にスクロールバーを追加するクラスと使用例を次に示します。オブジェクトを作成し、Frame
目的の (x, y) 座標に配置できます。次に、 in の代わりにオブジェクトを渡すだけでFrame
、目的の座標にスクロール可能なウィンドウを作成できます。root
main.frame
from tkinter import *
class ScrollableFrame:
"""A scrollable tkinter frame that will fill the whole window"""
def __init__ (self, master, width, height, mousescroll=0):
self.mousescroll = mousescroll
self.master = master
self.height = height
self.width = width
self.main_frame = Frame(self.master)
self.main_frame.pack(fill=BOTH, expand=1)
self.scrollbar = Scrollbar(self.main_frame, orient=VERTICAL)
self.scrollbar.pack(side=RIGHT, fill=Y)
self.canvas = Canvas(self.main_frame, yscrollcommand=self.scrollbar.set)
self.canvas.pack(expand=True, fill=BOTH)
self.scrollbar.config(command=self.canvas.yview)
self.canvas.bind(
'<Configure>',
lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
)
self.frame = Frame(self.canvas, width=self.width, height=self.height)
self.frame.pack(expand=True, fill=BOTH)
self.canvas.create_window((0,0), window=self.frame, anchor="nw")
self.frame.bind("<Enter>", self.entered)
self.frame.bind("<Leave>", self.left)
def _on_mouse_wheel(self,event):
self.canvas.yview_scroll(-1 * int((event.delta / 120)), "units")
def entered(self,event):
if self.mousescroll:
self.canvas.bind_all("<MouseWheel>", self._on_mouse_wheel)
def left(self,event):
if self.mousescroll:
self.canvas.unbind_all("<MouseWheel>")
# Example usage
obj = ScrollableFrame(
master,
height=300, # Total required height of canvas
width=400 # Total width of master
)
objframe = obj.frame
# use objframe as the main window to make widget