滚动条列表框

0 投票
2 回答
1024 浏览
提问于 2025-04-18 05:02

我正在尝试创建一个弹出窗口,里面有一个带滚动条的列表框。但是,我不明白为什么在运行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()

2 个回答

0

问题(或者说问题的一部分)是你创建了两个 Tk 类的实例。一个 tkinter 程序只需要一个 Tk 的实例。

1

正如Bryan Oakley之前所说,问题的一部分在于有多个类的实例。我觉得对象也是不必要的。下面是一个简单的例子,可以正常工作:

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

我发现这个网站这个网站在我需要用Tkinter做东西的时候非常有用。祝你好运!

撰写回答