New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Comments
When I use small font_size
in pygame.font.SysFont()
, error happeds as following. Now the version of pygame is 2.0.3
.
Python 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 13:42:17)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
pygame 2.0.3 (SDL 2.0.16, Python 3.6.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> pygame.init()
(5, 0)
>>> font = pygame.font.SysFont('arial', 6, True)
>>> txt = font.render('A', True, (255,255,255))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pygame.error: Text has zero width
>>> font = pygame.font.SysFont('arial', 8, True)
>>> txt = font.render('A', True, (255,255,255))
>>>
But when I use pygame==2.0.0
, the above error will not appear. My environment is:
- system version: Mac 10.15.6
- pygame version: 2.0.0 (work) & 2.0.3 (not work)
- python version: 3.6.9
I have tested and reproduced on my Intel MacBook Pro (running 12.0.1) with the following results:
Pygame 2.0.1 and below — issue does not occur
Pygame 2.0.2 and above — issue does occur (tested on both Python 3.9 and 3.10)
Also, this occurs with any font size lower than 8.
Tested on Windows 10 and I cannot reproduce using different versions of python/pygame so would indicate this is specific to Mac.
Since this is a mac sysfont regression, naturally, it’s most natural to suspect my PR changing how mac sysfont works. (To fix it taking 20 seconds to initialize on most systems).
But the error message makes me think it might be a different version of freetype interacting differently with SDL_ttf.
All my Sysfont fix should’ve done, at most, is change the font file fetched for «arial.» Does pygame.font.match_font("arial")
return something different on the different pygame versions? Does this happen with other fonts, from the system or not?
pygame.font.match_font("arial")
return something different on the different pygame versions?
Yes, there are different output on the different pygame versions.
>>> pygame.__version__
'2.0.3'
>>> pygame.font.match_font("arial")
'/System/Library/Fonts/Helvetica.ttc'
>>> pygame.__version__
'2.0.0'
>>> pygame.font.match_font("arial")
'/System/Library/Fonts/Supplemental/Arial.ttf'
Also, I try on other fonts and the issue only happens with arial
.
>>> font = pygame.font.SysFont('arial', 6, True)
>>> txt = font.render('A', True, (255,255,255))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pygame.error: Text has zero width
>>> font = pygame.font.SysFont('sfnstextcondensed', 6, True)
>>> txt = font.render('A', True, (255,255,255))
>>> font = pygame.font.SysFont('menlo', 6, True)
>>> txt = font.render('A', True, (255,255,255))
>>> font = pygame.font.SysFont('applesdgoth')
>>> txt = font.render('A', True, (255,255,255))
>>>
I also try to get the match_font
with other font, and menlo
as an example:
>>> pygame.__version__
'2.0.3'
>>> pygame.font.match_font("menlo")
'/System/Library/Fonts/Menlo.ttc'
>>> pygame.__version__
'2.0.0'
>>> pygame.font.match_font("menlo")
'/System/Library/Fonts/Menlo.ttc'
It looks like that the font file causes this issue?
In 2.0.3 it looks like it can’t find Arial, but it knows Helvetica is close.
If you try to render with Helvetica, that would crash on both versions?
Here’s my current theory:
- The way it finds font files was changed (by me, Overhaul SysFont on Mac #2594)
- It can’t find Arial, so it uses a Helvetica file. Because SysFont has an alias system, and the two are grouped together.
https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L300-L303 - The Helvetica file is always «broken» like this
If that’s right, it seems like the font directories I programmed it to look in need to be expanded. This code describes the locations it looks currently: https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L184-L196. In theory, this would be fixed by adding /System/Library/Fonts/Supplemental
to the list of locations. This is actually something you could put in as a PR.
It’s been a while, but I believe I used the «Font book» app on MacOS to see what locations had fonts in them, but it must be different between systems and between OS versions. So you could go through your «Font book» app, or use system_profiler -NSFontDataType
or something (I don’t remember which I used) to see all fonts in your system, and add any font directory paths that I didn’t.
Also thanks for going to the trouble to report this issue.
Looks like there is another font path there to search on Mac. Though I
guess with the problem last time l, of it taking forever to look through
font directories, not searching ‘fonts/supplemental’ is probably
intentional.
The previous implementation used a system call which could be really slow, system_profiler
. The new approach has a catalog of directories to search, and it looks like this one needs to be added. It’s not exempt from the search intentionally.
I add /System/Library/Fonts/Supplemental
in https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L184-L196 and it works. arial
finds the correct font file in the given path.
>>> import pygame
pygame 2.0.3 (SDL 2.0.16, Python 3.6.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> pygame.init()
(5, 0)
>>> font = pygame.font.SysFont('arial', 6, True)
>>> txt = font.render('A', True, (255,255,255))
>>> pygame.font.match_font("arial")
'/System/Library/Fonts/Supplemental/Arial.ttf'
>>>
But when it comes to helvetica
, though it finds a related font file, the error still happpens when I set font_size=6
.
>>> font = pygame.font.SysFont('helvetica', 6, True)
>>> txt = font.render('A', True, (255,255,255))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pygame.error: Text has zero width
>>> pygame.font.match_font("helvetica")
'/System/Library/Fonts/Helvetica.ttc'
>>> font = pygame.font.SysFont('helvetica', 8, True)
>>> txt = font.render('A', True, (255,255,255))
>>>
What happens if you try to render a longer string in Helvetica size 6?
…
On Tue, 9 Nov 2021, 11:09 Ming Zhang, ***@***.***> wrote:
I add /System/Library/Fonts/Supplemental in
https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L184-L196
and it works. arial finds the correct font file in the given path.
>>> import pygame
pygame 2.0.3 (SDL 2.0.16, Python 3.6.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> pygame.init()
(5, 0)
>>> font = pygame.font.SysFont(‘arial’, 6, True)
>>> txt = font.render(‘A’, True, (255,255,255))
>>> pygame.font.match_font(«arial»)
‘/System/Library/Fonts/Supplemental/Arial.ttf’
>>>
But when it comes to helvetica, though it finds a related font file, the
error still happpens when I set font_size=6.
>>> font = pygame.font.SysFont(‘helvetica’, 6, True)
>>> txt = font.render(‘A’, True, (255,255,255))
Traceback (most recent call last):
File «<stdin>», line 1, in <module>
pygame.error: Text has zero width
>>> pygame.font.match_font(«helvetica»)
‘/System/Library/Fonts/Helvetica.ttc’
>>> font = pygame.font.SysFont(‘helvetica’, 8, True)
>>> txt = font.render(‘A’, True, (255,255,255))
>>>
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#2827 (comment)>, or
unsubscribe
<https://github.com/notifications/unsubscribe-auth/ADGDGGVRULZDIZNKHAZWLK3ULD6ORANCNFSM5HSFLLDQ>
.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
@mingzhang96 would you like to add this fix to pygame yourself by opening a pull request?
Also, in the Font Book app on MacOS, you can go through your fonts and check there aren’t any other unsearched font directories on your OS and system.
The problem with Helvetica is something deep within SDL_TTF, and I think we shouldn’t worry about it too much.
@Starbuck5 So Sorry to reply so late. Please check the pr. I add a new path in sysfont.py
to avoid this issue.
pygame.error: Text has zero width #2827
Comments
When I use small font_size in pygame.font.SysFont() , error happeds as following. Now the version of pygame is 2.0.3 .
But when I use pygame==2.0.0 , the above error will not appear. My environment is:
- system version: Mac 10.15.6
- pygame version: 2.0.0 (work) & 2.0.3 (not work)
- python version: 3.6.9
The text was updated successfully, but these errors were encountered:
I have tested and reproduced on my Intel MacBook Pro (running 12.0.1) with the following results:
Pygame 2.0.1 and below — issue does not occur
Pygame 2.0.2 and above — issue does occur (tested on both Python 3.9 and 3.10)
Also, this occurs with any font size lower than 8.
Tested on Windows 10 and I cannot reproduce using different versions of python/pygame so would indicate this is specific to Mac.
Since this is a mac sysfont regression, naturally, it’s most natural to suspect my PR changing how mac sysfont works. (To fix it taking 20 seconds to initialize on most systems).
But the error message makes me think it might be a different version of freetype interacting differently with SDL_ttf.
All my Sysfont fix should’ve done, at most, is change the font file fetched for «arial.» Does pygame.font.match_font(«arial») return something different on the different pygame versions? Does this happen with other fonts, from the system or not?
pygame.font.match_font(«arial») return something different on the different pygame versions?
Yes, there are different output on the different pygame versions.
Also, I try on other fonts and the issue only happens with arial .
I also try to get the match_font with other font, and menlo as an example:
It looks like that the font file causes this issue?
In 2.0.3 it looks like it can’t find Arial, but it knows Helvetica is close.
If you try to render with Helvetica, that would crash on both versions?
Here’s my current theory:
- The way it finds font files was changed (by me,
Overhaul SysFont on Mac #2594 )
https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L300-L303
If that’s right, it seems like the font directories I programmed it to look in need to be expanded. This code describes the locations it looks currently: https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L184-L196. In theory, this would be fixed by adding /System/Library/Fonts/Supplemental to the list of locations. This is actually something you could put in as a PR.
It’s been a while, but I believe I used the «Font book» app on MacOS to see what locations had fonts in them, but it must be different between systems and between OS versions. So you could go through your «Font book» app, or use system_profiler -NSFontDataType or something (I don’t remember which I used) to see all fonts in your system, and add any font directory paths that I didn’t.
Also thanks for going to the trouble to report this issue.
Looks like there is another font path there to search on Mac. Though I
guess with the problem last time l, of it taking forever to look through
font directories, not searching ‘fonts/supplemental’ is probably
intentional.
The previous implementation used a system call which could be really slow, system_profiler . The new approach has a catalog of directories to search, and it looks like this one needs to be added. It’s not exempt from the search intentionally.
I add /System/Library/Fonts/Supplemental in https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L184-L196 and it works. arial finds the correct font file in the given path.
But when it comes to helvetica , though it finds a related font file, the error still happpens when I set font_size=6 .
@mingzhang96 would you like to add this fix to pygame yourself by opening a pull request?
Also, in the Font Book app on MacOS, you can go through your fonts and check there aren’t any other unsearched font directories on your OS and system.
The problem with Helvetica is something deep within SDL_TTF, and I think we shouldn’t worry about it too much.
Источник
Ошибка «Текст имеет нулевую ширину» после повторной инициализации отображения Pygame?
У меня есть проект в Pygame 1.9.2, где я повторно инициализирую дисплей несколько раз и рисую текст на поверхности дисплея. Он работает нормально, пока я не закрою дисплей Pygame и не выполню его повторную инициализацию.
Это следует за структурой как это:
Эта программа работает до тех пор, пока дисплей не будет закрыт в первый раз, а затем повторно инициализирован, после чего я получаю следующую ошибку при попытке использовать textFont.render :
Я рву волосы, пытаясь понять, что не так. Я знаю, что «Hello world!» имеет ширину больше нуля. Как мне исправить эту проблему?
2 ответа
Проблема в том, что pygame.quit() был вызван до того, как программа была закончена. Это вызывает каждый модуль Pygame (например, pygame.font ) быть неинициализированным.
Вместо того чтобы полагаться на pygame.quit чтобы закрыть экран Pygame, используйте pygame.display.quit в конце каждого while running петля. Затем положить pygame.quit в самом конце скрипта выгрузить остальные модули после того, как они будут использованы.
(Calling pygame.init() снова перед отображением текста не решит эту проблему, потому что это приводит к тому, что отображение Pygame перестает отвечать. (Это может быть ошибка в Pygame 1.9.2)
Я нашел решение, которое работало для меня: просто удалите элемент шрифта перед вызовом pygame.display.quit() т.е. просто del font каждый раз, когда вы закончите, используя его.
Элемент font — это тот, который вы создали с помощью команды:
Источник
Ошибка «Текст имеет нулевую ширину» после повторной инициализации отображения Pygame?
У меня есть проект в Pygame 1.9.2, где я повторно инициализирую дисплей несколько раз и рисую текст на поверхности дисплея. Он работает нормально, пока я не закрою дисплей Pygame и не выполню его повторную инициализацию.
Это следует за структурой, подобной этой:
Эта программа работает до тех пор, пока дисплей не будет закрыт в первый раз, а затем повторно инициализирован, после чего я получаю следующую ошибку при попытке использовать textFont.render :
Я рву волосы, пытаясь понять, что не так . Я знаю, что «Hello world!» имеет ширину больше нуля. Как мне решить эту проблему?
2 ответа
Проблема в том, что pygame.quit() был вызван до завершения программы. Это приводит к неинициализации каждого модуля Pygame (например, pygame.font ).
Вместо того чтобы полагаться на pygame.quit , чтобы закрыть экран Pygame, используйте pygame.display.quit в конце каждого цикла while running . Затем поместите pygame.quit в самый конец скрипта, чтобы выгрузить остальные модули после того, как они будут использованы.
(Повторный вызов pygame.init() перед отображением текста также не решит эту проблему, потому что это приводит к тому, что отображение Pygame перестает отвечать. (Это может быть ошибка в Pygame 1.9.2)
Я нашел решение, которое сработало для меня: просто удалите элемент шрифта перед вызовом pygame.display.quit() , то есть просто del font каждый раз, когда вы его используете.
Элемент font — это тот, который вы создали с помощью команды:
Источник
pygame.error: Text has zero width about pygame HOT 11 CLOSED
Comments (11)
I have tested and reproduced on my Intel MacBook Pro (running 12.0.1) with the following results:
Pygame 2.0.1 and below — issue does not occur
Pygame 2.0.2 and above — issue does occur (tested on both Python 3.9 and 3.10)
Also, this occurs with any font size lower than 8.
rethanon commented on January 13, 2023
Tested on Windows 10 and I cannot reproduce using different versions of python/pygame so would indicate this is specific to Mac.
Starbuck5 commented on January 13, 2023
Since this is a mac sysfont regression, naturally, it’s most natural to suspect my PR changing how mac sysfont works. (To fix it taking 20 seconds to initialize on most systems).
But the error message makes me think it might be a different version of freetype interacting differently with SDL_ttf.
All my Sysfont fix should’ve done, at most, is change the font file fetched for «arial.» Does pygame.font.match_font(«arial») return something different on the different pygame versions? Does this happen with other fonts, from the system or not?
mingzhang96 commented on January 13, 2023
pygame.font.match_font(«arial») return something different on the different pygame versions?
Yes, there are different output on the different pygame versions.
Also, I try on other fonts and the issue only happens with arial .
I also try to get the match_font with other font, and menlo as an example:
It looks like that the font file causes this issue?
Starbuck5 commented on January 13, 2023
In 2.0.3 it looks like it can’t find Arial, but it knows Helvetica is close.
If you try to render with Helvetica, that would crash on both versions?
Here’s my current theory:
- The way it finds font files was changed (by me, #2594)
- It can’t find Arial, so it uses a Helvetica file. Because SysFont has an alias system, and the two are grouped together.
https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L300-L303 - The Helvetica file is always «broken» like this
If that’s right, it seems like the font directories I programmed it to look in need to be expanded. This code describes the locations it looks currently: https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L184-L196. In theory, this would be fixed by adding /System/Library/Fonts/Supplemental to the list of locations. This is actually something you could put in as a PR.
It’s been a while, but I believe I used the «Font book» app on MacOS to see what locations had fonts in them, but it must be different between systems and between OS versions. So you could go through your «Font book» app, or use system_profiler -NSFontDataType or something (I don’t remember which I used) to see all fonts in your system, and add any font directory paths that I didn’t.
Also thanks for going to the trouble to report this issue.
MyreMylar commented on January 13, 2023
Starbuck5 commented on January 13, 2023
Looks like there is another font path there to search on Mac. Though I
guess with the problem last time l, of it taking forever to look through
font directories, not searching ‘fonts/supplemental’ is probably
intentional.
The previous implementation used a system call which could be really slow, system_profiler . The new approach has a catalog of directories to search, and it looks like this one needs to be added. It’s not exempt from the search intentionally.
mingzhang96 commented on January 13, 2023
I add /System/Library/Fonts/Supplemental in https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L184-L196 and it works. arial finds the correct font file in the given path.
But when it comes to helvetica , though it finds a related font file, the error still happpens when I set font_size=6 .
MyreMylar commented on January 13, 2023
Starbuck5 commented on January 13, 2023
@mingzhang96 would you like to add this fix to pygame yourself by opening a pull request?
Also, in the Font Book app on MacOS, you can go through your fonts and check there aren’t any other unsearched font directories on your OS and system.
The problem with Helvetica is something deep within SDL_TTF, and I think we shouldn’t worry about it too much.
mingzhang96 commented on January 13, 2023
@Starbuck5 So Sorry to reply so late. Please check the pr. I add a new path in sysfont.py to avoid this issue.
Related Issues (20)
- Rework `pygame._sdl2.video.get_drivers()`
- Add «ABGR» format to `pygame.image.fromstring` HOT 2
- `pygame.image.frombuffer` should take a stride argument
- Renaming (to|from)string C functions to (to|from)bytes
- SystemError when disconnecting and reconnecting usb controller HOT 3
- Allow mixer.music.set_pos() for sounds created from a sound array HOT 3
- replace Rect for FRect HOT 1
- replace Rect for FRect
- metadata-generation-failed HOT 4
- Fix docs build
- Port SDL_mixer metadata functionality HOT 1
- Umm I tried installing pygame and it gave me this error code I didn’t really get if it was problem from my DLLs files or something was missing. Pls i need directions HOT 4
- Improve `pygame.sprite.AbstractGroup` by preferring `self.spritedict` over `self.sprites()` where possible HOT 1
- Replace `SDL_GetTicks` with `SDL_GetTicks64` in `time.c` HOT 3
- pygame.transform.blur
- Trouble with pip installing pygame. Please help. HOT 3
- About add load spine animation function HOT 2
- Pygame website is down HOT 1
- Pygame and .ttf Files Left Open
- Segfault in `PixelArray` when trying to access surface after closing the PixelArray
Recommend Projects
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
TensorFlow
An Open Source Machine Learning Framework for Everyone
Django
The Web framework for perfectionists with deadlines.
Laravel
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
server
A server is a program made to process requests and deliver data to clients.
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Visualization
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
Recommend Org
We are working to build community through open source technology. NB: members must have two-factor auth.
Microsoft
Open source projects and samples from Microsoft.
Источник
When I use small font_size
in pygame.font.SysFont()
, error happeds as following. Now the version of pygame is 2.0.3
.
Python 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 13:42:17)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
pygame 2.0.3 (SDL 2.0.16, Python 3.6.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> pygame.init()
(5, 0)
>>> font = pygame.font.SysFont('arial', 6, True)
>>> txt = font.render('A', True, (255,255,255))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pygame.error: Text has zero width
>>> font = pygame.font.SysFont('arial', 8, True)
>>> txt = font.render('A', True, (255,255,255))
>>>
But when I use pygame==2.0.0
, the above error will not appear. My environment is:
- system version: Mac 10.15.6
- pygame version: 2.0.0 (work) & 2.0.3 (not work)
- python version: 3.6.9
I have tested and reproduced on my Intel MacBook Pro (running 12.0.1) with the following results:
Pygame 2.0.1 and below — issue does not occur
Pygame 2.0.2 and above — issue does occur (tested on both Python 3.9 and 3.10)
Also, this occurs with any font size lower than 8.
Tested on Windows 10 and I cannot reproduce using different versions of python/pygame so would indicate this is specific to Mac.
Since this is a mac sysfont regression, naturally, it’s most natural to suspect my PR changing how mac sysfont works. (To fix it taking 20 seconds to initialize on most systems).
But the error message makes me think it might be a different version of freetype interacting differently with SDL_ttf.
All my Sysfont fix should’ve done, at most, is change the font file fetched for «arial.» Does pygame.font.match_font("arial")
return something different on the different pygame versions? Does this happen with other fonts, from the system or not?
pygame.font.match_font("arial")
return something different on the different pygame versions?
Yes, there are different output on the different pygame versions.
>>> pygame.__version__
'2.0.3'
>>> pygame.font.match_font("arial")
'/System/Library/Fonts/Helvetica.ttc'
>>> pygame.__version__
'2.0.0'
>>> pygame.font.match_font("arial")
'/System/Library/Fonts/Supplemental/Arial.ttf'
Also, I try on other fonts and the issue only happens with arial
.
>>> font = pygame.font.SysFont('arial', 6, True)
>>> txt = font.render('A', True, (255,255,255))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pygame.error: Text has zero width
>>> font = pygame.font.SysFont('sfnstextcondensed', 6, True)
>>> txt = font.render('A', True, (255,255,255))
>>> font = pygame.font.SysFont('menlo', 6, True)
>>> txt = font.render('A', True, (255,255,255))
>>> font = pygame.font.SysFont('applesdgoth')
>>> txt = font.render('A', True, (255,255,255))
>>>
I also try to get the match_font
with other font, and menlo
as an example:
>>> pygame.__version__
'2.0.3'
>>> pygame.font.match_font("menlo")
'/System/Library/Fonts/Menlo.ttc'
>>> pygame.__version__
'2.0.0'
>>> pygame.font.match_font("menlo")
'/System/Library/Fonts/Menlo.ttc'
It looks like that the font file causes this issue?
In 2.0.3 it looks like it can’t find Arial, but it knows Helvetica is close.
If you try to render with Helvetica, that would crash on both versions?
Here’s my current theory:
- The way it finds font files was changed (by me, #2594)
- It can’t find Arial, so it uses a Helvetica file. Because SysFont has an alias system, and the two are grouped together.
https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L300-L303 - The Helvetica file is always «broken» like this
If that’s right, it seems like the font directories I programmed it to look in need to be expanded. This code describes the locations it looks currently: https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L184-L196. In theory, this would be fixed by adding /System/Library/Fonts/Supplemental
to the list of locations. This is actually something you could put in as a PR.
It’s been a while, but I believe I used the «Font book» app on MacOS to see what locations had fonts in them, but it must be different between systems and between OS versions. So you could go through your «Font book» app, or use system_profiler -NSFontDataType
or something (I don’t remember which I used) to see all fonts in your system, and add any font directory paths that I didn’t.
Also thanks for going to the trouble to report this issue.
Looks like there is another font path there to search on Mac. Though I
guess with the problem last time l, of it taking forever to look through
font directories, not searching ‘fonts/supplemental’ is probably
intentional.
Worth mentioning that you don’t have to use sysfont to load fonts. It is a
helper module for making apps slightly easier to use cross platform if you
don’t care exactly what font the end text uses. If you want control just
use the font or freetype modules directly. Just in case you aren’t aware.
…
Looks like there is another font path there to search on Mac. Though I
guess with the problem last time l, of it taking forever to look through
font directories, not searching ‘fonts/supplemental’ is probably
intentional.
The previous implementation used a system call which could be really slow, system_profiler
. The new approach has a catalog of directories to search, and it looks like this one needs to be added. It’s not exempt from the search intentionally.
I add /System/Library/Fonts/Supplemental
in https://github.com/pygame/pygame/blob/main/src_py/sysfont.py#L184-L196 and it works. arial
finds the correct font file in the given path.
>>> import pygame
pygame 2.0.3 (SDL 2.0.16, Python 3.6.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> pygame.init()
(5, 0)
>>> font = pygame.font.SysFont('arial', 6, True)
>>> txt = font.render('A', True, (255,255,255))
>>> pygame.font.match_font("arial")
'/System/Library/Fonts/Supplemental/Arial.ttf'
>>>
But when it comes to helvetica
, though it finds a related font file, the error still happpens when I set font_size=6
.
>>> font = pygame.font.SysFont('helvetica', 6, True)
>>> txt = font.render('A', True, (255,255,255))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pygame.error: Text has zero width
>>> pygame.font.match_font("helvetica")
'/System/Library/Fonts/Helvetica.ttc'
>>> font = pygame.font.SysFont('helvetica', 8, True)
>>> txt = font.render('A', True, (255,255,255))
>>>
What happens if you try to render a longer string in Helvetica size 6?
…
@mingzhang96 would you like to add this fix to pygame yourself by opening a pull request?
Also, in the Font Book app on MacOS, you can go through your fonts and check there aren’t any other unsearched font directories on your OS and system.
The problem with Helvetica is something deep within SDL_TTF, and I think we shouldn’t worry about it too much.
@Starbuck5 So Sorry to reply so late. Please check the pr. I add a new path in sysfont.py
to avoid this issue.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
Я пытаюсь написать текстовое приключение, основанное исключительно на графическом интерфейсе (есть поля, в которых отображается текст, а также кнопки, по которым вы можете нажимать для перемещения и атаки). У меня возникли небольшие проблемы с отображением ящиков. Ниже приведены оскорбительные строки кода:
Соответствующая переменная из импорта в следующем файле:
textWhite = (240, 234, 214)
Где происходит ошибка
from globalvars import *
import pygame
class AbstractBanner:
def __init__(self, centerX, centerY, width, height, color):
self.leftX = centerX - width//2
self.topY = centerY - height//2
self.width = width
self.height = height
self.color = color
self.gameDisplay = pygame.display.set_mode((scrW, scrH))
class Banner(AbstractBanner):
def __init__(self, centerX, centerY, width, height, color, text, textSize):
super().__init__(centerX, centerY, width, height, color)
self.text = text
self.textObject = pygame.font.SysFont("arial.ttf", textSize)
def display(self):
surface = self.textObject.render(self.text, True, textWhite)
rect = surface.get_rect()
rect.center = (self.leftX, self.topY)
self.gameDisplay.blit(surface, rect)
pygame.draw.rect(self.gameDisplay, self.color, (self.leftX, self.topY, self.width, self.height))
Усеченная версия, где выполняется приведенный выше код (без игрового цикла):
class screenDisplay():
def __init__(self):
self.state = "TITLE_SCREEN"
self.states = ["TITLE_SCREEN", "MAIN_GAME", "COMBAT", "CUTSCENE"]
if self.state == self.states[0]:
self.showTitleScreen()
def showTitleScreen(self):
#Background
background = Banner(scrW//2, scrH//2, scrW, scrH, avocado, " ", 2)
background.display()
И здесь, в четвертом .py файле, находится игровой цикл, который выполняет вышеуказанное:
import pygame
import time
from screenDisplay import screenDisplay
import globalvars
# pylint: disable=no-member
pygame.init()
# pylint: enable=no-member
clock = pygame.time.Clock()
showGame = screenDisplay()
while not globalvars.gameIsDone:
for event in pygame.event.get():
# pylint: disable=no-member
if event.type == pygame.QUIT:
done = True
pygame.quit()
# pylint: enable=no-member
pygame.display.update()
clock.tick(30)
Я прочитал этот вопрос о SO, но я не знаю, куда мне поместить строку del
или даже что я должен удалить. Если решение состоит в том, чтобы поместить эти две строки в один файл, есть ли альтернативы?
РЕДАКТИРОВАТЬ: О, и самое главное, здесь ошибка!
Traceback (most recent call last):
File "c:UsersRobertsonDesktopPersonal ProjectspytextrpggameLauncher.py", line 9, in <module>
showGame = screenDisplay()
File "c:UsersRobertsonDesktopPersonal ProjectspytextrpgscreenDisplay.py", line 9, in __init__
self.showTitleScreen()
File "c:UsersRobertsonDesktopPersonal ProjectspytextrpgscreenDisplay.py", line 26, in showTitleScreen
background.display()
File "c:UsersRobertsonDesktopPersonal ProjectspytextrpgBanner.py", line 19, in display
surface = self.textObject.render(self.text, True, textWhite)
pygame.error: Text has zero width
pygame.quit()
не выходит из программы — он только выходит / закрывается pygame
— это означает, что он удаляет элементы pygame
из памяти.
Но после закрытия pygame он все равно выполняет pygame.display.update()
, что создает проблему.
Поэтому вам нужно exit()
или sys.exit()
после pygame.quit()
для немедленного выхода из программы.
if event.type == pygame.QUIT:
pygame.quit()
exit()
#sys.exit()
Или вы должны выйти из цикла while
— используя скорее globalvars.gameIsDone = True
вместо done = True
, а затем использовать pygame.quit()
— аналогично ответу @ 9000.
while not globalvars.gameIsDone:
for event in pygame.event.get():
# pylint: disable=no-member
if event.type == pygame.QUIT:
globalvars.gameIsDone = True
# pylint: enable=no-member
pygame.display.update()
clock.tick(30)
pygame.quit()
0
furas
1 Апр 2019 в 20:33
Я пытаюсь написать текстовое приключение, полностью основанное на графическом интерфейсе (есть поля, отображающие текст, а также кнопки, на которые вы можете нажимать, чтобы двигаться и атаковать). У меня небольшие проблемы с отображением моих ящиков
Ниже приведены оскорбительные строки кода:
Соответствующая переменная из импорта в следующем файле:
textWhite = (240, 234, 214)
Где происходит ошибка
from globalvars import *
import pygame
class AbstractBanner:
def __init__(self, centerX, centerY, width, height, color):
self.leftX = centerX - width//2
self.topY = centerY - height//2
self.width = width
self.height = height
self.color = color
self.gameDisplay = pygame.display.set_mode((scrW, scrH))
class Banner(AbstractBanner):
def __init__(self, centerX, centerY, width, height, color, text, textSize):
super().__init__(centerX, centerY, width, height, color)
self.text = text
self.textObject = pygame.font.SysFont("arial.ttf", textSize)
def display(self):
surface = self.textObject.render(self.text, True, textWhite)
rect = surface.get_rect()
rect.center = (self.leftX, self.topY)
self.gameDisplay.blit(surface, rect)
pygame.draw.rect(self.gameDisplay, self.color, (self.leftX, self.topY, self.width, self.height))
Усеченная версия выполнения приведенного выше кода (без игрового цикла):
class screenDisplay():
def __init__(self):
self.state = "TITLE_SCREEN"
self.states = ["TITLE_SCREEN", "MAIN_GAME", "COMBAT", "CUTSCENE"]
if self.state == self.states[0]:
self.showTitleScreen()
def showTitleScreen(self):
#Background
background = Banner(scrW//2, scrH//2, scrW, scrH, avocado, " ", 2)
background.display()
А здесь, в четвертом файле .py, находится игровой цикл, выполняющий описанное выше:
import pygame
import time
from screenDisplay import screenDisplay
import globalvars
# pylint: disable=no-member
pygame.init()
# pylint: enable=no-member
clock = pygame.time.Clock()
showGame = screenDisplay()
while not globalvars.gameIsDone:
for event in pygame.event.get():
# pylint: disable=no-member
if event.type == pygame.QUIT:
done = True
pygame.quit()
# pylint: enable=no-member
pygame.display.update()
clock.tick(30)
Я прочитал вопрос это на SO, но я не знаю, где я должен поставить строку del или даже что я должен удалить. Если решение включает в себя размещение этих двух строк в одном файле, есть ли альтернативы?
Обновлено: О, и самое главное, вот ошибка!
Traceback (most recent call last):
File "c:UsersRobertsonDesktopPersonal ProjectspytextrpggameLauncher.py", line 9, in <module>
showGame = screenDisplay()
File "c:UsersRobertsonDesktopPersonal ProjectspytextrpgscreenDisplay.py", line 9, in __init__
self.showTitleScreen()
File "c:UsersRobertsonDesktopPersonal ProjectspytextrpgscreenDisplay.py", line 26, in showTitleScreen
background.display()
File "c:UsersRobertsonDesktopPersonal ProjectspytextrpgBanner.py", line 19, in display
surface = self.textObject.render(self.text, True, textWhite)
pygame.error: Text has zero width
Mark Reed
unread,
Dec 23, 2009, 3:20:08 AM12/23/09
to pygame…@seul.org
I’m running pygame in a thread, killing the thread and reloading it.
Second time in we throw an exception with font.render. I have no
experience with C, but I would like to debug the problem which appears
to be in font_render since both times the python pygame.font.render
arguments are the same. I’m also now using the 1.9.1 win release, 1.8
had the same exact behavior.
If I compile the pygame source on windows using the cygwin environment
I should be able to debug it and step through the font_render C code
right? Or at least put printfs inside the font.c code?
If I use different pygame code that uses font.render in the thread I
don’t see this problem. Is it possible bad python code could be
corrupting pointers in the pygame C code?
Should I not be running pygame in a thread then killing it and
restarting it multiple times in the same process? I assume if this was
bad I’d see more random problems than this.
Mark
Brian Fisher
unread,
Dec 23, 2009, 4:27:22 AM12/23/09
to pygame…@seul.org
running pygame in a thread and then killing it and restarting it multiple times is not a well tested path. I would expect that is why you you are running into weird and unusual problems. Also note, the various platforms (PC, Mac, Linux) often have their own odd problems with running window management code in multiple threads — just a note if cross-platformness is important to you.
Practically speaking, what you probably want to do is:
a) find another way to do what you want without shutting down and restarting pygame and possibly without a separate thread even.
b) treat this as a pygame bug — i.e. try to make a minimal sample that demonstrates the problem for somebody (possibly even you) to use for debugging.
Jake b
unread,
Dec 23, 2009, 6:54:53 AM12/23/09
to pygame…@seul.org
Maybe it could help to explicitly call pygame.quit before thread kill.
Why do you need this? Might be able to remove that requirement.
—
Jake
Mark Reed
unread,
Dec 23, 2009, 10:48:19 PM12/23/09
to pygame…@seul.org
Thanks for the reply,
It made me try calling pygame.init() then pygame.display.init() and
pygame.display.quit() in the main thread which fixed the problem.
Obviously calling pygame.init() and pygame.quit() was overkill for
starting and restarting the pygame thread.
Mark
flank…@gmail.com
unread,
May 15, 2016, 1:13:07 AM5/15/16
to pygame mirror on google groups, pygame…@seul.org, markr…@gmail.com
I found a solution that worked for me: just delete the font element before calling pygame.display.quit(). Every time.
The font element is the one you created using the command:
pygame.font.Font(None, font_size)
abant…@gmail.com
unread,
Jul 31, 2020, 8:59:43 PM7/31/20
to pygame mirror on google groups
Sir may I know how to delete that element because I’m facing the same problem right now.