2

I had an requirement for creating dynamic buttons in tkinter window,But i tried Scroll bar option which is not helping me to scroll the buttons in the tkinter window,Is any other option to scroll the Dynamic buttons.

Code:

root = tkinter.Tk()
root.title("Links-Shortcut")
root.configure(background="gray99")
sw= tkinter.Scrollbar(root) 
sw.pack(side=RIGHT, fill=Y)


os.chdir("C:\Bo_Link")
with open('Bo_ol_links.csv', 'r', newline='') as fo:
    lis=[line.strip('\r\n').split(',') for line in fo]        # create a list of lists
lis=sorted(lis)
    #print (lis)

for i,x in enumerate(lis):
    btn = tkinter.Button(root,height=1, width=20,relief=tkinter.FLAT,bg="gray99",fg="purple3",font="Dosis",text=lis[i][0],command=lambda i=i,x=x: openlink(i))
    btn.pack(padx=10,pady=5,side=tkinter.TOP)

def openlink(i):
    os.startfile(lis[i][1])

root.mainloop()

Thanks.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
Shiva
  • 531
  • 4
  • 6
  • 14
  • 1
    It would make it a _lot_ easier for people to help you if you posted a small example program that focuses on your dynamic buttons problem. Please see [MCVE]. – PM 2Ring Aug 01 '15 at 14:22
  • That's *much* better, although you left out the `import` statements, and it's not easy for others to run your code as we don't have "C:\Bo_Link" or 'Bo_ol_links.csv'. – PM 2Ring Aug 01 '15 at 16:35

2 Answers2

6

This code packs buttons into a scrollable Frame that I stole from found at the Tkinter Unpythonic Wiki. I'm running it on Python 2, so I use Tkinter as the module name in the import statement, for Python 3 change that statement to use tkinter.

import Tkinter as tk

class VerticalScrolledFrame(tk.Frame):
    """A pure Tkinter scrollable frame that actually works!

    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling
    """
    def __init__(self, parent, *args, **kw):
        tk.Frame.__init__(self, parent, *args, **kw)            

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = tk.Scrollbar(self, orient=tk.VERTICAL)
        vscrollbar.pack(fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)
        canvas = tk.Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = tk.Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=tk.NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())

        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)


root = tk.Tk()
root.title("Scrollable Frame Demo")
root.configure(background="gray99")

scframe = VerticalScrolledFrame(root)
scframe.pack()

lis = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
for i, x in enumerate(lis):
    btn = tk.Button(scframe.interior, height=1, width=20, relief=tk.FLAT, 
        bg="gray99", fg="purple3",
        font="Dosis", text='Button ' + lis[i],
        command=lambda i=i,x=x: openlink(i))
    btn.pack(padx=10, pady=5, side=tk.TOP)

def openlink(i):
    print lis[i]

root.mainloop()
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
3

Believe it or not, the simplest solution for a vertical stack of buttons might be to add the buttons to a text widget. You can do the frame-in-a-canvas solution which gives a lot of flexibility, but it's a bit more work. Using a text widget as a container doesn't give much flexibility with respect to layout, but it's very easy if all you need is a vertical stack of widgets.

Here is a working example:

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        text = tk.Text(self, wrap="none")
        vsb = tk.Scrollbar(orient="vertical", command=text.yview)
        text.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        text.pack(fill="both", expand=True)

        for i in range(20):
            b = tk.Button(self, text="Button #%s" % i)
            text.window_create("end", window=b)
            text.insert("end", "\n")

        text.configure(state="disabled")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()
Community
  • 1
  • 1
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685