首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python显示和翻转图像

使用python显示和翻转图像
EN

Stack Overflow用户
提问于 2017-09-23 21:37:05
回答 1查看 555关注 0票数 0

我正在尝试将字符串编码为二维码。然后使用python在显示器上显示二维码图像。

下面是我的代码:

代码语言:javascript
复制
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")不是常量。它将被更新(例如,I get string from mysql)。当字符串更新时,我希望在3秒后显示新的二维码图像,然后翻转它,然后继续。

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

代码语言:javascript
复制
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来中断。

代码语言:javascript
复制
Traceback (most recent call last):
File "qr.py", line 18, in <module>
sleep(5)
KeyboardInterrupt

提前谢谢你。

EN

回答 1

Stack Overflow用户

发布于 2017-09-24 01:47:26

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

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

代码语言:javascript
复制
img = pygame.image.load("QR.png").convert()

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

要实现计时器,可以使用pygame.time.get_tickstime.sleep使你的程序没有响应,通常不应该在游戏中使用。

下面是一个例子:

代码语言:javascript
复制
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()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46380162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档