【问题标题】:Inserting a button into a tkinter listbox on python?将按钮插入到 python 上的 tkinter 列表框中?
【发布时间】:2011-04-10 14:00:36
【问题描述】:
...
self.myListbox=tkinter.Listbox() 
self.myListbox.pack()
self.myButton=tkinter.Button(self.myListbox,text="Press")

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

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

【问题讨论】:

    标签: python listbox tkinter


    【解决方案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()
    

    【讨论】:

      【解决方案2】:

      你不能。来自列表框文档:“列表框是显示字符串列表的小部件”。

      当然,您可以使用 pack、place 或 grid 在小部件内放置一个按钮,但它不会成为列表框数据的一部分——例如,它不会滚动,并且可能会掩盖一些数据.

      【讨论】:

      • 你有没有其他可以求婚的选择?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      相关资源
      最近更新 更多