我正在尝试将字符串编码为二维码。然后使用python在显示器上显示二维码图像。
下面是我的代码:
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秒后显示新的二维码图像,然后翻转它,然后继续。
但是,当我将代码放入循环中时,它崩溃了,图像不会翻转或更新。
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


提前谢谢你。
发布于 2017-09-24 01:47:26
pygame.display.flip不会翻转图像,它会更新显示/屏幕。要真正翻转图像,您必须使用pygame.transform.flip。
还有各种其他问题,例如,您应该在while循环开始之前进行初始化、调用pygame.display.set_mode并加载图像。加载图片后,调用convert或convert_alpha方法来提高blit性能:
img = pygame.image.load("QR.png").convert()您还需要调用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()https://stackoverflow.com/questions/46380162
复制相似问题