Search code examples
pythonlistobjecttkinter

Beginner Python: Display objects in list within GUI window using tkinter


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.


Solution

  • 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 :)