Reputation: 41
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
Upvotes: 0
Views: 89
Reputation: 912
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 (i.e., 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:
Upvotes: 0
Reputation: 5289
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")
Upvotes: 1