简体   繁体   中英

QRCode displaying in tkinter GUI python

I am trying to display a QR Code in a tkinter GUI, however when I execute this code:

import tkinter as tk
from PIL import Image,ImageTk
import pyqrcode
from tkinter.font import Font
import random


root=tk.Tk()
root.title("QR Lottery")
root.config(bg="white")

# Defining Fonts
TitleFont = Font(family="HEX:gon Staggered 2", size="48")

def generateQR():
    num=random.randint(1,2)
    if num==1:
        QRCode=pyqrcode.create("You Win!")
        QRCode.png("QRCode.png",scale=8)
        img = Image.open('QRCode.png')
        QRCodeImg = ImageTk.PhotoImage(img)
        QRCodeLabel=tk.Label(image=QRCodeImg)
        QRCodeLabel.grid(row=2,column=1)
    else:
        QRCode=pyqrcode.create("You Lose!")
        QRCode.png("QRCode.png",scale=8)
        img = Image.open('QRCode.png')
        QRCodeImg = ImageTk.PhotoImage(img)
        QRCodeLabel=tk.Label(image=QRCodeImg)
        QRCodeLabel.grid(row=2,column=1)

#Labels
TitleLabel=tk.Label(text="qr lottery",bg="white",font=TitleFont)
TitleLabel.grid(row=1,column=1,columnspan=5)
ButtonQR=tk.Button(text="Generate!",bg="white",command=generateQR)
ButtonQR.grid(row=3,column=1)

root.mainloop()

The Image Label produced is a blank square. I am unsure of why this is, as I left the background color blank.

Question : The Image Label produced is a blank square. I am unsure of why this is

A :You must keep a reference to the image object in your Python program, by attaching it to another object.

Use the following:


  1. Define your own widget QRCodeLabel by inherit from tk.Label .
    Init only with parameter parent

     class QRCodeLabel(tk.Label): def __init__(self, parent, qr_data): super().__init__(parent) print('QRCodeLabel("{}")'.format(qr_data)) 
  2. Create your QRCode with the passed qr_data and save as PNG file.

      qrcode = pyqrcode.create(qr_data) tmp_png_file = "QRCode.png" qrcode.png(tmp_png_file, scale=8) 
  3. Create a image object from the PNG file.
    Tkinter can handle PNG image files by its own, no PIL needed.

    NOTE : You have to use self.image to prevent garbage collection!

      self.image = tk.PhotoImage(file=tmp_png_file) 
  4. Configure this Label with the self.image

      self.configure(image=self.image) 

Usage :

 class App(tk.Tk): def __init__(self): super().__init__() buttonQR = tk.Button(text="Generate!", bg="white", command=self.generateQR) buttonQR.grid(row=2, column=0) self.qr_label = None def generateQR(self): if self.qr_label: self.qr_label.destroy() self.qr_label = QRCodeLabel(self, random.choice(["You Win!", "You Lose!"])) self.qr_label.grid(row=1, column=0) if __name__ == "__main__": App().mainloop() 

Tested with Python: 3.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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