简体   繁体   中英

Why do I get this error when inserting element into listbox in python

I'm trying to insert an element into a ListBox when a button is pressed. However when the button is pressed I keep getting an error.

So this is my code:

import tkinter as tk

class One(object):

    def __init__(self, root):

        root.title('TEST')

        mainFrame = tk.Frame(root, width="500", height = "500")

        LB = tk.Listbox(mainFrame, height="22")
        LB.pack()

        select = tk.Button(mainFrame, text="Add", command = self.add)
        select.pack()

        mainFrame.pack()

    def add(self):
        One.__init__.LB.insert(0, "100")

def main():
    root = tk.Tk()
    app = One(root)
    root.geometry("500x500")
    root.mainloop()

if __name__ == '__main__':
    main()

And when I run it I get the following error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:/Users/Leo Muller/Desktop/plottertest2.py", line 20, in add
    One.__init__.LB.insert(0, "100")
AttributeError: 'function' object has no attribute 'LB'

I'm not sure where I have gone wrong

Because as you have your class currently configured, LB is a local variable, accessible only from within the __init__() function. It cannot be accessed the way you tried.

You'll want to add self. to the naming to change it to an attribute, so that it can be accessed from anywhere:

class One(object):

    def __init__(self, root):
        root.title('TEST')

        mainFrame = tk.Frame(root, width="500", height = "500")

        self.LB = tk.Listbox(mainFrame, height="22")
        self.LB.pack()

        select = tk.Button(mainFrame, text="Add", command = self.add)
        select.pack()

        mainFrame.pack()

    def add(self):
        self.LB.insert(0, "100")

As the backtrace is telling you, the problem is with this line:

One.__init__.LB.insert(0, "100")

You are trying to access the LB attribute of One 's constructor method (ie, One.__init__ . The method doesn't have an attribute LB . LB is a locally-scoped variable in your constructor.

What you probably meant was something like:

class One(object):

    def __init__(self, root):
        # ...
        self.LB = tk.Listbox(mainFrame, height="22")
        self.LB.pack()
        # ...

    def add(self):
        self.LB.insert(0, "100")

By the looks of things, I'm guessing you're fairly new to Python. I'd recommend walking through an introduction or two. There are plenty available online. Here are a few leads:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM