简体   繁体   English

为什么这个程序的 window 打开后立即关闭

[英]why the window of this program closes immediately after opening

I ran this code for testing if it works and continue but I saw this closes immediately after opening why what is the problem here I checked many different things What is wrong in this code?我运行此代码以测试它是否有效并继续,但我看到它在打开后立即关闭为什么这里有什么问题我检查了许多不同的东西这段代码有什么问题? How to fix that?如何解决?

import pygame
import random
pygame.init()
x=480
y=680
tick=pygame.time.Clock()
x_change=0
red=(0,0,255)
green=(0,255,0)
white=(255,255,255)
graphic=pygame.display.set_mode((700,700))
graphic.fill(green)
noexit=True
while noexit:
    pygame.draw.rect(graphic,white,(x,y,20,20))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            noexit=False
        elif event.type==pygame.KEYDOWN:
            if event.key==K_RIGHT:
                x_change=+2
            elif event.key==K_LEFT:
                x_change=-2
        elif event.type==pygame.KEYUP:
            if event.key==K_RIGHT or event.key==K_LEFT:
                x_change=0
    tick.tick(60)

pygame.quit()
quit()

Suggestions:建议:

  1. You should use sys.你应该使用 sys.
import sys

...

sys.quit()
  1. Like as https://stackoverflow.com/users/14531062/matiiss said, you should add pygame.正如https://stackoverflow.com/users/14531062/matiiss所说,您应该添加pygame. to all the consonants that come from pygame.来自 pygame 的所有辅音。

  2. You might consider use pgzero (pygame zero) because it is easier.您可能会考虑使用 pgzero (pygame zero),因为它更容易。

Errors:错误:

  1. There is a syntax error in lines 22 and 27 where it's += and -= not =+ and =- .第 22 和 27 行存在语法错误,其中+=-=不是=+=-

  2. Just remove quit.只需删除退出。

Here's what your converted code might look like from all the suggestions and errors:以下是所有建议和错误中转换后的代码的样子:

import pgzrun #this line imports pygame zero
import random
import pygame

pygame.init()

x=480
y=680

rect1 = Rect(x, y, 20, 20)

tick=pygame.time.Clock()

def draw(): #you don't have to call draw or update in pygame zero
    screen.clear()
    screen.fill("green")
    screen.draw.filled_rect(rect1, "white")

def update():
    global rect1
    if keyboard.right:
        rect1.x += 2
    elif keyboard.left:
        rect1.x -= 2

    tick.tick(60)

pgzrun.go()

NOTES:笔记:

Since pygame zero is a third-party program, install it in the command terminal.由于pygame零是第三方程序,在命令终端安装。

Windows: pip install pgzero Mac: pip3 install pgzero Windows:pip 安装 pgzero Mac:pip3 安装 pgzero

You might need to learn pygame zero to understand the code.您可能需要学习 pygame 零才能理解代码。 Go to https://pygame-zero.readthedocs.io/en/stable/ to learn more about pygame zero. Go 到https://pygame-zero.readthedocs.io/en/stable/了解有关 pygame 零的更多信息。

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

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