0

I am trying use the code on Kivy website to learn Texture. However, the following code on kivy website has a type problem:

texture = Texture.create(size=(64, 64))

size = 64 * 64 * 3
buf = [int(x * 255 / size) for x in range(size)]

buf = b''.join(map(chr, buf))    # This is the code with a problem

texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')
with self.canvas:
    Rectangle(texture=texture, pos=self.pos, size=(64, 64))

Because b''.join() only accepts bytes-like object not str and chr returns str, I got this Error: TypeError: sequence item 0: expected a bytes-like object, str found I am using Python 3.7 and Kivy 1.11.1. Am I missing something here? I copied the exact code on this page: https://kivy.org/doc/stable/api-kivy.graphics.texture.html

Jaxon
  • 164
  • 9
  • Could that line not simply be replaced with `buf = bytes(buf)`? Looks like it was Python 2.x code that has compatibility issues with 3.x (see https://stackoverflow.com/questions/4523505/chr-equivalent-returning-a-bytes-object-in-py3k) – Oliver.R Mar 16 '20 at 04:20

1 Answers1

1

Here is a version of that example that works with python3:

    # create a 64x64 texture, defaults to rgba / ubyte
    texture = Texture.create(size=(64, 64))

    # create 64x64 rgb tab, and fill with values from 0 to 255
    # we'll have a gradient from black to white
    size = 64 * 64 * 3
    buf = bytes([int(x * 255 / size) for x in range(size)])

    # then blit the buffer
    texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')

    # that's all ! you can use it in your graphics now :)
    # if self is a widget, you can do this
    with self.canvas:
        Rectangle(texture=texture, pos=self.pos, size=(64, 64))

Perhaps that example should be reported to the Kivy developers.

John Anderson
  • 35,991
  • 4
  • 13
  • 36