Error: "NameError: name 'self' is not defined" when using exec() to create several buttons in tkinter

53 Views Asked by At

I am trying to create a GUI for a cribbage program that I made a while back. I want to fan the cards out at the beginning so the player can select where they would like to cut the deck. To avoid individually declaring and packing 52 different frames and buttons manually, I used a for loop and the exec() method to create each button and frame and also pass an integer into the method in the command= parameter of the buttons. It works as intended to create all of the buttons, but when I click on one of the cards, the NameError is raised.

def cut(self, i):
    self.select_card_frame.place_forget()
    for k in range(52):
        exec(f'self.cut_frame_{k}.place_forget()')
    return i


def start_cut(self):
    global cut_image
    cut_image = self.resize_card('cards/back_of_card.png')
    self.select_card_frame = Frame(self.window)
    self.select_card_label = Label(self.select_card_frame, text='Select Card to Cut', font=20)
    self.select_card_label.pack()
    self.select_card_frame.place(x=450, y=50)
    for i in range(52):
        exec(f'self.cut_frame_{i} = Frame(self.window)')
        exec(f'self.cut_label_{i} = Button(self.cut_frame_{i}, image=cut_image, command=lambda: self.cut({i}))')
        exec(f"self.cut_label_{i}.pack(side='left')")
        exec(f'self.cut_frame_{i}.place(x={i*20}, y=100)')

I have tried making a few of the card buttons individually and it worked as it should, so I suspect it is something that I am doing wrong with the exec() method. Any ideas on what I am doing wrong? or is there a better way to do this without using exec()? or do I just have to suck it up and type out the extra 300 lines of code? This is what the window looks like for a better picture of what I am trying to do. Deck fanned out for cut

0

There are 0 best solutions below