tkinter.Listbox scrolbar yview

时间:2016-08-22 16:24:24

标签: python tkinter listbox python-3.5

我再次遇到编写Python的一些问题,并希望寻求我的帮助。我继续构建我的Listbox小部件但无法设置滚动条。我可以将滚动条放在正确的位置,但是,上下只是没有工作并弹出错误说"对象()不带参数"。任何人都可以建议如何解决它?我附上以下代码供参考。

import tkinter
from tkinter import *

def test():
    root = tkinter.Tk()
    lst = ['1', '2', '  3', '4', '5', '  6', '7', '8', '  9', '10']
    a = MovListbox(root, lst)
    a.grid(row=0, column=0, columnspan=2, sticky=tkinter.N)
    root.mainloop()

class MovListbox(tkinter.Listbox):

    def __init__(self, master=None, inputlist=None):
        super(MovListbox, self).__init__(master=master)

        # Populate the news category onto the listbox
        for item in inputlist:
            self.insert(tkinter.END, item)

        #set scrollbar
        s = tkinter.Scrollbar(master, orient=VERTICAL, command=tkinter.YView)
        self.configure(yscrollcommand=s.set)
        s.grid(row=0, column=2, sticky=tkinter.N+tkinter.S)

if __name__ == '__main__':
    test()

1 个答案:

答案 0 :(得分:1)

首先,您不需要import tkinterfrom tkinter import *

  • 使用import表示您需要tkinter.'function'来调用函数 来自tkinter
  • 使用from表示您可以像调用该函数一样调用该函数 开始时没有tkinter.的程序
  • 使用*表示从tkinter获取所有功能

此外,我已根据Rawig的回答修复了代码

import tkinter

def test():
    root = tkinter.Tk()
    lst = ['1', '2', '  3', '4', '5', '  6', '7', '8', '  9', '10']
    a = MovListbox(root, lst)
    a.grid(row=0, column=0, columnspan=2, sticky=tkinter.N)
    root.mainloop()

class MovListbox(tkinter.Listbox):

    def __init__(self, master=None, inputlist=None):
        super(MovListbox, self).__init__(master=master)

        # Populate the news category onto the listbox
        for item in inputlist:
            self.insert(tkinter.END, item)

        #set scrollbar
        s = tkinter.Scrollbar(master, orient=VERTICAL, command=self.yview)
        self.configure(yscrollcommand=s.set)
        s.grid(row=0, column=2, sticky=tkinter.N+tkinter.S)

if __name__ == '__main__':
    test()