Skip to content Skip to sidebar Skip to footer

Inserting A Button Into A Tkinter Listbox On Python?

... self.myListbox=tkinter.Listbox() self.myListbox.pack() self.myButton=tkinter.Button(self.myListbox,text='Press') self.myListbox.insert(1,myButton.pack()) ... I want to inser

Solution 1:

You can't. From the listbox documentation: "A listbox is a widget that displays a list of strings".

You can, of course, use pack, place or grid to put a button inside the widget but it won't be part of the listbox data -- it won't scroll for example, and might obscure some of the data.

Solution 2:

An alternative to a ListBox is a scrollable frame;

import functools
try:
    from tkinter import *

    import tkinter as tk
except ImportError: 
    from Tkinter import *
    import Tkinter as tk#

window = Tk()
frame_container=Frame(window)

canvas_container=Canvas(frame_container, height=100)
frame2=Frame(canvas_container)
myscrollbar=Scrollbar(frame_container,orient="vertical",command=canvas_container.yview) # will be visible if the frame2 is to to big for the canvas
canvas_container.create_window((0,0),window=frame2,anchor='nw')

deffunc(name):
    print (name)
mylist = ['item1','item2','item3','item4','item5','item6','item7','item8','item9']
for item in mylist:
    button = Button(frame2,text=item,command=functools.partial(func,item))
    button.pack()


frame2.update() # update frame2 height so it's no longer 0 ( height is 0 when it has just been created )
canvas_container.configure(yscrollcommand=myscrollbar.set, scrollregion="0 0 0 %s" % frame2.winfo_height()) # the scrollregion mustbe the size of the frame inside it,#in this case "x=0 y=0 width=0 height=frame2height"#width 0 because we only scroll verticaly so don't mind about the width.

canvas_container.pack(side=LEFT)
myscrollbar.pack(side=RIGHT, fill = Y)

frame_container.pack()
window.mainloop()

Post a Comment for "Inserting A Button Into A Tkinter Listbox On Python?"