简体   繁体   中英

Create 2d array in Tkinter

I'm just working on a new project in Python with Tkinter. I'm a newbie in Python, so I need some help. I want to create 2D array and show it in a window.

Here is my code:

maze =[[player(), invisblock(), invisblock(), invisblock()],
      [invisblock(),invisblock(),invisblock(), invisblock()],
      [invisblock(), invisblock(), invisblock(), invisblock()],
      [invisblock(), invisblock(), invisblock(), invisblock()],  ]

Player looks like:

def player():
    block = tkinter.Label(window)
    block.image = tkinter.PhotoImage(file="down.png")
    block['image'] = block.image
    block.config(text='karel_down')
    return block

And printing like:

def printt():
    for i, block_row in enumerate(map):
        for j, block in enumerate(block_row):
            block.grid(row=i, column=j)
    window.update()
    window.after(250)

Everything works fine, but I have a small problem. I want to make another function like this (this is not functional right now):

def create_world(row,col):
    for i in range(row):
        for j in range(col):
             maze[i][j] = invisblock()

So I want to fill all my maze with row and col from create_world with invisblock(). Example: create_world(10,10) and will create maze 10x10 invisblock(). I don't want to fill manually like in my first code sample (maze =[[player()...) but with a function. In short, I want to create the initial array of objects "smarter". Thanks!!

You can use list comprehensions:

def create_world(row,col):
    return [[invisiblock() for i in range(col)] for j in range(row)] 

maze = create_world(10, 10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM