Lam Nguyen Lam Nguyen - 28 days ago 9
Python Question

Show and flip image using python

I am trying to encode a String to a QR code. Then show the QR code image on a display using python.

Here is my code:

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)


Now I want to display and flip the image in a loop.

I want to do it in a loop as the string ("This is a string one") is not constant. It will be updated (such as, I get string from mysql). When the string updates, I want to display the new QR code image after
3
seconds then flip it, then continue.

But when I put the code in a loop, it crashes and the image does not flip or update.

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)


Update:

After 5 second, pygame-windows not flip. I must use Ctrl-C to Interrupt.

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


enter image description here
enter image description here
Thank you in advance.

Answer Source

I think you can fix like this:

import pyqrcode

from PIL import Image

import os

import pygame

from time import sleep

def abc():
    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").convert()
    scr.blit(img,(0,0))
    pygame.display.flip()
    sleep(3)
    pygame.quit() #add only command
while(1):
    abc()