我正在尝试将桌面中存在的图像加载到pygame中,但这只会给我一个错误

时间:2019-09-29 08:15:22

标签: python pygame

  • 我想知道为什么我在此代码中遇到错误。
  • 我正在尝试上载JPG格式的字符,这给我一个错误。
  • 我正在使用IDLE,它是python 3.7.3
    import pygame
    pygame.init() #Initialize the game

    win = pygame.display.set_mode((1000,700)) # Sets the window size

    pygame.display.set_caption("First Game") # Title of window in the string

    *walkRight = [pygame.image.load('Person.JPG')]* # load image

    x = 100
    y = 690
    width = 10
    height = 10
    vel = 5
    isJump = False
    jumpCount = 5 # timer for mid-air
    left = False
    right = False

    run = True
    while run:
        pygame.time.delay(100) # waits for 100 miliseconds = 0.1 second

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and x > vel: # left
            x -= vel
        if keys[pygame.K_RIGHT] and x < 500 - width - vel: # right
            x += vel
        if not(isJump): # not jumping
            if keys[pygame.K_SPACE]:
                isJump = True

        else:
            if jumpCount >= -5:
                checker = 1 # positive jumpCount
                if jumpCount < 0:
                    checker = -1 # negative jumpcount
                y -= (jumpCount ** 2) * 0.5 * checker
                jumpCount -= 1
            else:
                isJump = False # allows the player to jump again
                jumpCount = 5 # how long it is in mid air

        win.fill((255,255,255)) # Fills the screen black
        pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
        pygame.display.update() # updates the screen each time

    pygame.quit()

为什么标有*的地方给我一个错误?

1 个答案:

答案 0 :(得分:0)

由于您没有提到正在使用的操作系统,因此我将尝试在Windows和Linux上提供帮助。如果您在代码中提到了文件的正确路径,则使用哪个操作系统都没有关系。

有多种方法可以在不同的操作系统中获取绝对文件路径:

例如

  1. 在Windows上,按住Shift键并右键单击图像,然后单击“复制为路径”。

  2. 在Linux上,只需右键单击图像,然后单击“复制”。

现在返回您的代码并粘贴完整的图像路径。 仅举一个例子,完整路径应类似于Windows上的“ C:\ Users \ userName \ Downloads \ image.png” “ / home / username / Desktop / image。 png”

为避免在Linux中使用用户名,您可以将“ / home / username” 替换为“〜/” ,这样您的完整路径应类似于“〜 /Desktop/image.png”

注意:如果计划共享代码或在生产服务器/远程服务器上运行代码,则绝对不建议使用硬代码路径。但是,如果您只是在学习和尝试,那应该可以解决问题。