[Solved] How to use multiple objects? [closed]


It took me quite some time to figure out what you want to do. If you haven’t found a solution to your problem yet, here is some code to try out.

The first thing you should do is declare a global variable to store all maze blocks.

blocks = [] # create a list for the maze blocks

Then we will need to functions for building and destroying the maze. You already have a similar structure in your code example (destroythemhehe and mazebuilder) but we can greatly improve readability and performance here.

def gamephase():
    global menu, quit, block
    menu = Button(root, text="Menu", relief=RIDGE, bg='#C90', command=menuevent)
    menu.place(x=50, y=540)
    quit = Button(root, text="Quitter", relief=RIDGE, bg='#C90', command=destroy_maze)
    quit.place(x=670, y=540)
    generate = Button(root, text="Generer", relief=RIDGE, bg='#C90', command=build_maze)
    generate.place(x=360, y=540)

The function for building the maze is not really complicated:

def build_maze():
    global blocks
    for x in range(17):
        for y in range(25):
            if zone[x][y]:
                b = Label(root, image=block)
                b.place(x=20 + y * 30, y=20 + x * 30) # a formula which calculates the position of the block
                blocks.append(b) # add the block to the list

It does basically the same thing as your function mazebuilder but it saves all the Labels to the blocks list which is much cleaner than your blocker function. Now we need a function to destroy the blocks:

def destroy_maze():
    global blocks
    for x in blocks: # destroy each block
        x.destroy()
    blocks = []

And we are done! This should work as expected but I haven’t tested it thoroughly.

You can make your code even prettier if you use classes instead of global variables. This can also help you prevent some nasty bugs.

1

solved How to use multiple objects? [closed]