Reputation: 43
I have a program that populates lists based on user input. These lists are actually lists of objects that have 2 values: name and amount.
I'm currently running tkinter and trying to return these lists in a readable format in the GUI. Here's what I have so far:
from tkinter import *
from tkinter import ttk
Containers =[]
Lids = []
Wicks = []
Labels = []
Misc = []
Items = [Containers, Lids, Wicks, Labels, Misc]
class item(object):
#Constructor
def __init__(self, name, amount):
self.name = name
self.amount = amount
#Accessors
def getName(self):
return self.name
def getAmount(self):
return self.amount
def addItem(*args):
s = name.get()
global new_item
new_item = item(s, 0)
return new_item
Containers.append(new_item)
name = StringVar()
amount = StringVar()
remove_item = StringVar()
add_amount = StringVar()
subtract_amount = StringVar()
...#Leaving out all the frame information
t = Text(mainframe, width=60)
for item in Containers:
t.insert(END, item)
t.grid(column = 1, columnspan = 3, row = 10, padx = 5, pady = 10)
root.bind('<Return>', addItem())
root.mainloop()
What happens when I try to run the following is that I get an error: 'item' object is not callable
t = Text(mainframe, width=60)
for item in Containers:
t.insert(END, item)
t.grid(column = 1, columnspan = 3, row = 10, padx = 5, pady = 10)
How can I print these lists in the main GUI window?
Upvotes: 0
Views: 2830
Reputation: 25895
The problem is in your bind:
root.bind('<Return>', addItem())
When this line is evaluated addItem will return an item object at- return new_item
- and when you hit return python will try to call new_item. What you wrote is essentially:
new_item = additem()
root.bind('<Return>', new_item)
And there is no reason at all to use a global var if you're returning the item. What you meant is :
root.bind('<Return>', addItem)
so when you hit return the function addItem is called. Here you might think you need the global var but there are probably better ways, like encapsulating your entire application in a class. You have a lot of wrong in your code, so I suggest you work on it some before asking better questions. For example:
Containers.append(new_item)
is never called because it is after a return, also you have yet to put an input field which is what you probably meant to bind, not root, so actual input can be given. Google some Tk examples.
Upvotes: 1