Julia
Julia

Reputation: 39

How to return the value of self in a class?

I have a class called buttongen which generates buttons based on the rooms within a building. The rooms will be assessed and have the results stored in a database. How can I return the value of the text on the button to store in a variable? Each time I try to store the results for the rooms its giving the error TypeError: __init__() missing 2 required positional arguments: 'i' and 'row'.

EDIT: Included the section of code where the building is searched and the buttons are generated

    def search():
        global screen13
        global btn
        screen13 = Tk()
        screen13.geometry("300x250")
        screen13.title("Rooms")
        sitename3_info = sitename.get().strip()
        if sitename3_info:
            cursor = cnn.cursor()
            # combine the two SQL statements into one
            sql = ("SELECT roomname FROM rooms, Sites "
                   "WHERE rooms.siteID_fk2 = Sites.siteID AND siteName = %s")
            cursor.execute(sql, [sitename3_info])
            rooms = cursor.fetchall()
            # remove previous result (assume screen13 contains only result)
            for w in screen13.winfo_children():
                w.destroy()
            if rooms:
                for i, row in enumerate(rooms):
                    buttongen(i, row)
            else:
                Label(screen13, text="No room found").grid()

    class buttongen():
        def __init__(self,i,row):
            # creates a self generated amount of buttons which correspond to the amount of rooms in the table.
            self.i = i
            self.row = row
    
            self.roomname = self.row[0]
            self.btn = Button(screen13, text = self.roomname, command=lambda :[print(self.roomname), action()])
            self.btn.grid(row=i, column=0)
        def showroomname(self):
            print(self.roomname)

how can I store what text is on the button in roomclicked_info = buttongen()

Upvotes: 1

Views: 621

Answers (2)

MrBhuyan
MrBhuyan

Reputation: 161

To initialize the object of buttongen() you need to pass the two required parameters as defined in def __init__(self,i,row): the i and row.

As you are creating the object with roomclicked_info = buttongen(), you are not specifying the i and row parameters in buttongen(). You can pass the values of i and row here, like roomclicked_info = buttongen(i, row).

Upvotes: 2

xx liu
xx liu

Reputation: 34

the right code may like this:

i = 10   # the i you want
row = 10 # the row you want
roomclicked_info = buttongen(i, row)

class buttongen need 2 required positional arguments.

Upvotes: 2

Related Questions