tkinter.Listbox scrolbar yview

五迷三道 提交于 2019-12-24 01:59:16

问题


I again encounter some problems in writing Python and would like to seek my help. I continue to build my Listbox widget but cannot setup a scrollbar. I can put the Scrollbar in the right position, however, the up and down just don't work out and pop up an error saying "Object() takes no parameter". Could anyone advise how to fix it? I attached the code below for reference.

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:


first of all you don't need both import tkinter and from tkinter import *

  • Using import means you need tkinter.'function' to call a function from tkinter
  • Using from means you can call the function as if it were in your program without the tkinter. at the start
  • Using * means taking all functions from tkinter

Also I have fixed the code based on Rawig's answer

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


来源:https://stackoverflow.com/questions/39084403/tkinter-listbox-scrolbar-yview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!