Tkinter: Scrollable buttons
Fredrik Lundh
fredrik at pythonware.com
Thu Oct 7 02:39:26 EDT 1999
sragsdale at my-deja.com wrote:
> I've got a big panel full of buttons and such, and I need to add a
> scroll bar so that I can move up and down the list. The following code
> will construct something that _looks_ good, but the scrollbar won't
> actually do anything. Any idea what's wrong?
set the canvas scrollregion. the following example
shows you one way to do this (it's setting things up
so the canvas will track changes to the frame. if the
frame is static, you can set the scrollregion once).
</F>
#
# scrolled frame
#
# fredrik lundh, april 1998
#
# fredrik at pythonware.com
# http://www.pythonware.com
#
from Tkinter import *
class ScrolledFrame(Frame):
def __init__(self, master, **kw):
apply(Frame.__init__, (self, master), kw)
# create the widgets
scrollbar = Scrollbar(self, orient=VERTICAL)
self.canvas = Canvas(
self,
bd=0, highlightthickness=0,
yscrollcommand=scrollbar.set,
bg="red"
)
scrollbar.config(command=self.canvas.yview)
scrollbar.pack(fill=Y, side=RIGHT)
self.canvas.pack(expand=1, fill=BOTH, side=LEFT, )
# reset the view
# (always do this if you don't use scrollbars)
self.canvas.xview("moveto", 0)
self.canvas.yview("moveto", 0)
# create the inner frame
self.inner = Frame(self.canvas, bg="blue")
# track changes to its size
self.inner.bind('<Configure>', self.__configure)
# place the frame inside the canvas (this also
# runs the __configure method)
self.canvas.create_window(0, 0, window=self.inner, anchor=NW)
def __configure(self, event):
# update the scrollbars to match the size of the inner frame
size = self.inner.winfo_reqwidth(), self.inner.winfo_reqheight()
self.canvas.config(scrollregion="0 0 %s %s" % size)
# --------------------------------------------------------------------
# test stuff
root = Tk()
f = ScrolledFrame(
root,
bd=2, relief=SUNKEN,
highlightthickness=2
)
f.pack(expand=1, fill=BOTH)
t = Text(
f.inner,
bg="gold",
height=100, width=40,
bd=0, highlightthickness=0
)
t.pack(expand=1, fill=BOTH)
for i in range(100):
t.insert(END, "line %d\n" % (i+1))
root.mainloop()
More information about the Python-list
mailing list