繁体   English   中英

使用python显示和翻转图像

[英]Show and flip image using python

我正在尝试将String编码为QR码。 然后使用python在显示屏上显示QR码图像。

这是我的代码:

import pyqrcode
from PIL import Image
import os
import pygame
from time import sleep

qr = pyqrcode.create("This is a string one")
qr.png("QR.png", scale=16)
pygame.init()
WIDTH = 1280
HEIGHT = 1080
scr = pygame.display.set_mode((WIDTH,HEIGHT),0,32)
img = pygame.image.load("QR.png")
scr.blit(img,(0,0))
pygame.display.flip()
sleep(3)

现在,我想循环显示和翻转图像。

我想循环执行此操作,因为字符串(“ This is a string one”)不是恒定的。 它将被更新(例如,我从mysql获取字符串)。 字符串更新后,我想在3秒后显示新的QR码图像,然后翻转它,然后继续。

但是,当我将代码放入循环中时,它会崩溃并且图像不会翻转或更新。

import pyqrcode

from PIL import Image

import os

import pygame

from time import sleep

while(1):

    qr = pyqrcode.create("Nguyen Tran Thanh Lam")

    qr.png("QR.png", scale=16)

    pygame.init()

    WIDTH = 1280

    HEIGHT = 1080

    scr = pygame.display.set_mode((WIDTH,HEIGHT),0,32)

    img = pygame.image.load("QR.png")

    scr.blit(img,(0,0))

    pygame.display.flip()

    sleep(5)

更新:

5秒钟后,pygame-windows无法翻转。 我必须使用Ctrl-C来中断。

Traceback (most recent call last):
File "qr.py", line 18, in <module>
sleep(5)
KeyboardInterrupt

在此处输入图片说明 在此处输入图片说明 先感谢您。

pygame.display.flip不翻转图像,而是更新显示/屏幕。 要真正翻转图像,您必须使用pygame.transform.flip

还有其他各种问题,例如,您应该进行初始化,调用pygame.display.set_mode并在while循环开始之前加载图像。 加载图像后,调用convertconvert_alpha方法以提高blit性能:

img = pygame.image.load("QR.png").convert()

您还需要调用pygame.event.pump()或对pygame.event.pump()的事件使用事件循环for event in pg.event.get():否则,该程序将冻结,因为操作系统认为您的程序已停止响应。

要实现计时器,您可以使用pygame.time.get_ticks time.sleep使程序无响应,通常不应在游戏中使用。

这是一个例子:

import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()  # A clock to limit the frame rate.

    image = pg.Surface((100, 100))
    image.fill((50, 90, 150))
    pg.draw.rect(image, (120, 250, 70), (20, 20, 20, 20))

    previous_flip_time = pg.time.get_ticks()
    done = False

    while not done:
        for event in pg.event.get():
            # Close the window if the users clicks the close button.
            if event.type == pg.QUIT:
                done = True

        current_time = pg.time.get_ticks()
        if current_time - previous_flip_time > 1000:  # 1000 milliseconds.
            # Flip horizontally.
            image = pg.transform.flip(image, True, False)
            previous_flip_time = current_time

        screen.fill((30, 30, 30))
        screen.blit(image, (100, 200))

        # Refresh the display/screen.
        pg.display.flip()
        clock.tick(30)  # Limit frame rate to 30 fps.


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

暂无
暂无

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

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