【问题标题】:Scroll Bar Listbox滚动条列表框
【发布时间】:2014-05-01 18:34:56
【问题描述】:

我正在尝试创建一个包含带有滚动条的列表框的弹出窗口。但是,我不明白为什么在 Python 中运行代码时什么都没有显示。一如既往,非常感谢!

from Tkinter import *

def run():
    # create the root and the canvas
    root = Tk()
    canvasW, canvasH = 300, 200
    canvas = Canvas(root, width=canvasW, height=canvasH)
    canvas.pack()
    class Struct: pass
    canvas.data = Struct()
    init(canvas)
    root.mainloop()  

def init(canvas):
    master = Tk()
    # use width x height + x_offset + y_offset (no spaces!)
    master.geometry("240x180+130+180")
    # create the listbox (height/width in char)
    listbox = Listbox(master, width=20, height=6)
    listbox.grid(row=0, column=0)
    # create a vertical scrollbar to the right of the listbox
    yscroll = Scrollbar(command=listbox.yview, orient=VERTICAL)
    yscroll.grid(row=0, column=1, sticky='ns')
    listbox.configure(yscrollcommand=yscroll.set)
    # now load the listbox with data
    numbers = ["1", "2", "3"]
    for item in numbers:
        # insert each new item to the end of the listbox
        listbox.insert(END, item)
run()

【问题讨论】:

    标签: python listbox tkinter scrollbar


    【解决方案1】:

    正如 Bryan Oakley 之前所说,部分问题在于 Tk 类的多个实例。我认为Canvas 对象也是不必要的。这是一个有效的简单案例:

    from Tkinter import *
    
    class MyList(object):
        def __init__(self, master=None):
            self.master = master
    
            self.yscroll = Scrollbar(master, orient=VERTICAL)
            self.yscroll.pack(side=RIGHT, fill=Y)
    
            self.list = Listbox(master, yscrollcommand=self.yscroll.set)
            for item in xrange(100):
                self.list.insert(END, item)
            self.list.pack(side=LEFT, fill=BOTH, expand=1)
    
            self.yscroll.config(command=self.list.yview)
    
    def run():
        root = Tk()
    
        app = MyList(root)
        root.mainloop()
    
    run()
    

    我发现 this sitethis site 在我必须使用 Tkinter 制作东西时非常有用。祝你好运!

    【讨论】:

      【解决方案2】:

      问题(或部分问题)是您正在创建Tk 类的两个实例。一个 tkinter 程序只需要一个 Tk 的实例。

      【讨论】:

        猜你喜欢
        • 2016-07-25
        • 2021-09-20
        • 2011-08-04
        • 1970-01-01
        • 2017-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多