[英]Create 2d array in Tkinter
I'm just working on a new project in Python with Tkinter. 我正在使用Tkinter在Python中开发一个新项目。 I'm a newbie in Python, so I need some help.
我是Python的新手,因此需要一些帮助。 I want to create 2D array and show it in a window.
我想创建2D数组并将其显示在窗口中。
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(). 所以我想用invisblock()从create_world的row和col填充所有迷宫。 Example: create_world(10,10) and will create maze 10x10 invisblock().
示例:create_world(10,10)并将创建10x10 invisblock()迷宫。 I don't want to fill manually like in my first code sample (maze =[[player()...) but with a function.
我不想像我的第一个代码示例(迷宫= [[player()...))那样手动填充,而是使用一个函数。 In short, I want to create the initial array of objects "smarter".
简而言之,我想创建对象“ 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.