简体   繁体   English

Python-使用函数获取图像大小将返回错误

[英]Python - getting image size with function returns error

I am quite new to python and I was trying to get the height of an image using a function copied from another post, so that I can correctly position the image in the window for a game I am making with PyGame. 我是python的新手,我试图使用从另一篇文章中复制的函数来获取图像的高度,以便可以将图像正确放置在窗口中,以便使用PyGame制作游戏。 Any ideas? 有任何想法吗?

Code: 码:

http://pastebin.com/atZ6vbZQ (get_image_size copied from here ) http://pastebin.com/atZ6vbZQ (从此处复制get_image_size)

Error: 错误:

Traceback (most recent call last): File "Game/game.py", line 67, in displayCar((display_width / 2), (display_height - (get_image_size(Lightning).height))) File "Game/game.py", line 22, in get_image_size with open(fname, 'rb') as fhandle: TypeError: coercing to Unicode: need string or buffer, pygame.Surface found 追溯(最近一次通话最近):文件“ Game / game.py”,第67行,位于displayCar((display_width / 2),(display_height-(get_image_size(Lightning).height)))文件“ Game / game.py”在get_image_size中的第22行,其中open(fname,'rb')作为句柄:TypeError:强制转换为Unicode:需要字符串或缓冲区,pygame.Surface

get_image_size(fname) expects file name but you use Lightning which is pygame.Surface() object get_image_size(fname)需要file name但是您使用的是Lightning ,它是pygame.Surface()对象


But pygame.Surface() is very useful you can get its size (and position) as pygame.Rect() object 但是pygame.Surface()非常有用,您可以将其大小(和位置)作为pygame.Rect()对象获取

Lightning_rect = Lightning.get_rect()

and then you have image size and position 然后你有图像的大小和位置

Lightning_rect.width
Lightning_rect.height
Lightning_rect.x
Lightning_rect.y
Lightning_rect.left
Lightning_rect.right
Lightning_rect.top
Lightning_rect.bottom

Lightning_rect.center 

etc. 等等

You can change position using 您可以使用更改位置

Lightning_rect.x = new_x
Lightning_rect.y = new_y

or 要么

Lightning_rect.topleft = (new_x, new_y)

And draw/blit 然后画/画

gameDisplay.blit(Lightning, Lightning_rect)

if you want to center image on screen then 如果要在屏幕上居中放置图像,则

gameDisplay_rect = gameDisplay.get_rect()

Lightning_rect.center = gameDisplay_rect.center

BWT: you can use Rect() to check collision with another Rect() ( pygame.Rect.colliderect ) or point ( pygame.Rect.collidepoint ) - ie. BWT:您可以使用Rect()检查与另一个Rect()( pygame.Rect.colliderect )或点( pygame.Rect.collidepoint )的pygame.Rect.collidepoint -即 with mouse position to build button. 用鼠标位置建立按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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