I want to use tkinter to display lists I am making in a simple window. However, I am unsure of the proper way to format this.
from tkinter import *
import tkinter as tk
from tkinter import messagebox
from tkinter import simpledialog
root = tk.Tk()
root.withdraw()
class Survey:
def __init__(self, width, length):
self.length = length
self.width = width
def setLength(self, length):
self.length = length
def setWidth(self, width):
self.width = width
def calArea(self):
return self.length * self.width
def describe(self):
return (f"length:",self.length, "width:", self.width, "area:", self.calArea())
areaList = []
lot1 = Survey(32.3, 35.0)
areaList.append(lot1)
lot2 = Survey(52.6, 46.1)
areaList.append(lot2)
lot3 = Survey(39.8, 57.2)
areaList.append(lot3)
window = Tk()
window.title("Survey Results")
window.geometry('300x300')
for x in range(0, len(areaList)):
text = Label(window, areaList[x])
text.grid(column=0, row=0)
Currently I am experiencing this error that I think needs me to change the list to a string, but I'm not sure how to do that here.
TypeError: argument of type 'Survey' is not iterable
My window opens, but it is empty. I tried text = Label(window, str(areaList[x]))
further errors put me in over my head.
CodePudding user response:
you are putting the instance of Survey inside a list and trying to take it out as a string without telling it what part you want out (aka the describe() function)
for x in range(0, len(areaList)):
text = Label(window, text=areaList[x].describe())
text.grid(column=0, row=0) ## this should be the same indentation
A better method of doing this skipping all the bad code habbits:
for sv in areaList: ##loops through the actual items in the list rather than the index:
Label(window, text=sv.describe()).grid(column=0, row=0) ## this can be 1 line if you dont need to do anything with the widget after.
Also you missed window.mainloop()
at the end of the code. not sure if thats just a copy/paste error or its actually missing
CodePudding user response:
object of class is nor iterable. use the code below:
from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
class Survey:
def __init__(self, width, length):
self.length = length
self.width = width
def calArea(self):
return self.length * self.width
def describe(self):
return (f"length:",self.length, "width:", self.width, "area:", self.calArea())
areaList = []
lot1 = Survey(32.3, 35.0)
areaList.append(lot1.describe())
lot2 = Survey(52.6, 46.1)
areaList.append(lot2.describe())
lot3 = Survey(39.8, 57.2)
areaList.append(lot3.describe())
window = Tk()
window.title("Survey Results")
window.geometry('300x300')
for x in range(0, len(areaList)):
text = Label(window, text=areaList[x])
text.pack()
window.mainloop()
have fun :)