python - 如何实现黑屏和网格绘制?

标签 python pygame

我有一个问题。这是我的代码:

import pygame
import tkinter as tk
class cube():
    rows = 20
    w = 500
    def __init__(self, start, dirnx=1, dirny=0, color=(255, 0, 0)):
        pass
class snake(object):
    def __init__(self, color, pos):
        pass
def drawGrid(w, rows, surface):
    b = 255
    sizeBtwn = w // rows
    x = 0
    y = 0
    for l in range(rows):
        x = x + sizeBtwn
        y = y + sizeBtwn
        pygame.draw.line(surface, (b, b, b), (x,0), (x,w))
        pygame.draw.line(surface, (b, b, b), (0,y), (w,y))
def redrawWindow(surface):
    global rows, width
    surface.fill((0,0,0))
    drawGrid(width, rows, surface)
    pygame.display.update()
def main():
    global width, rows
    width = 1280
    height = 720
    rows = 40
    win = pygame.display.set_mode((width, height))
    s = snake((255, 0, 0), (10, 10))
    run = True
    clock = pygame.time.Clock()
    while run:
        clock.tick(30)
        redrawWindow(win)
if __name__ == "__main__":
    main()

当我启动时,我什么都没有。我有一个灰色的 window 。但我应该有一个带有网格的黑色窗口...为什么什么也没有出现?

谢谢你帮助我!

最佳答案

您必须通过 pygame.event.pump() 来处理事件或pygame.event.get() .
该函数也不处理内部事件。这是保持系统响应和更新显示所必需的。

def main():
    # [...]

    clock = pygame.time.Clock()
    while run:

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

        clock.tick(30)
        redrawWindow(win)

关于python - 如何实现黑屏和网格绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60127387/

相关文章:

python - 数据帧的丢弃百分比 [pandas]

Python CSV 模块 - 引号丢失

python - python中变量是如何创建和销毁的?

python - 属性错误: 'Alien' object has no attribute 'image' (I am calling for a Group object)

Python/PyGame : Get window size

Python 2.7.2 全局变量 + tkinter

python - 在 python 存储库名称和包名称中使用连字符/破折号

python - 扭曲属性错误

python - Pygame 不会播放音频,但只有在作为守护进程运行时才会播放

python - 当我添加用作参数的组时,为什么会出现 nonetype 没有属性的属性错误