在python上将按钮插入tkinter列表框?

时间:2011-04-10 14:00:36

标签: python listbox tkinter

...
self.myListbox=tkinter.Listbox() 
self.myListbox.pack()
self.myButton=tkinter.Button(self.myListbox,text="Press")

self.myListbox.insert(1,myButton.pack())
...

我想在列表框中插入一个按钮,就像插入一个刺痛一样。我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

你做不到。从列表框文档中:“列表框是一个显示字符串列表的小部件”。

当然,您可以使用包,地点或网格在窗口小部件中放置一个按钮,但它不会成为列表框数据的一部分 - 例如,它不会滚动,并且可能会模糊某些数据

答案 1 :(得分:1)

ListBox的替代方法是可滚动框架;

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')

def func(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()