lordmauve / pgzero

A zero-boilerplate games programming framework for Python 3, based on Pygame.
https://pygame-zero.readthedocs.io/
GNU Lesser General Public License v3.0
536 stars 189 forks source link

"ValueError: substring not found" in textbox draw #250

Open keith-davies opened 3 years ago

keith-davies commented 3 years ago

Hey, I was recently digging around the text fitting source (ptext.py) and found an issue.

When calling screen.draw.textbox, if you prefix the string with a space(s), it will cause a ValueError exception to be thrown.

Without the space at the beginning, it works just fine.

Thank you for your time.

Source Code

import pgzrun

WIDTH  = 500
HEIGHT = 500

text = " ab"

def draw():
    screen.draw.textbox(text, (0, 0, 500, 500))

pgzrun.go()

Stack Trace

File "C:\..\issue.py", line 9, in draw
    screen.draw.textbox(text, (0, 0, 500, 500))
  File "C:\..\lib\site-packages\pgzero\screen.py", line 66, in textbox
    ptext.drawbox(*args, surf=self._surf, **kwargs)
  File "C:\..\lib\site-packages\pgzero\ptext.py", line 476, in drawbox
    fontsize = _fitsize(text, fontname, sysfontname, bold, italic, underline,
  File "C:\..\lib\site-packages\pgzero\ptext.py", line 162, in _fitsize
    if not fits(a):
  File "C:\..\lib\site-packages\pgzero\ptext.py", line 153, in fits
    texts = wrap(text, fontname, fontsize, sysfontname,
  File "C:\..\lib\site-packages\pgzero\ptext.py", line 109, in wrap
    a = text.index(" ", a) if " " in text else len(text)
ValueError: substring not found

System Information

Pygame 2.0.1 SDL 2.0.14, Python 3.9.2 Windows 10.0.19041.867

streetartist commented 3 years ago

Maybe using x = (cond) and TrueDo or FlaseDo is helpful

streetartist commented 3 years ago

And the code changes to a = (" " in text) and text.index(" ", a) or len(text)

streetartist commented 3 years ago

But I think both of them can work