Evilbitmap
Evilbitmap

Reputation: 37

How do I update pictures using Tkinter?

I've been having a problem with updating a picture in python using Tkinter. This program is creating a QR code and is displaying it on the window. I have no idea how to update it when it changes, the file name stays the same it just changes. This is what activates the creation of a QR code

def GenerateQRCode():
    # qr code maker 3000
    qr = qrcode.QRCode()
    qr.add_data("brush")
    img = qrcode.make(input.get())
    img.save("qrcode.png")
    resize_image = img.resize((150, 150))
    img2 = ImageTk.PhotoImage(img)
    label1 = Label(root, image=img2)
    label1.image = img2
    label1.pack(pady=50)

It does the job of creating the QR code and dispalying it, however, like I said, no clue how to update it while the file name would stay the same. I could make qrcode1.png, then if new QR code is requested, check if it exists, if so, delete it and make qrcode2.png and display it, viceversa. But I'm sure there is a way how to do it with just one file and maybe even creating the file might be unnecessary. Any comment is welcome. Thank you.

Upvotes: 2

Views: 511

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385870

You should create the label with the qr code once, and then update the label whenever you create the new qr code. Here's an example based off of your code:

import tkinter as tk
import qrcode
from PIL import ImageTk

def GenerateQRCode():
    global qr_image

    qr = qrcode.QRCode()
    qr.add_data("brush")
    img = qrcode.make(input.get())
    img.save("qrcode.png")

    resize_image = img.resize((150, 150))
    qr_image = ImageTk.PhotoImage(img)
    qr_label.configure(image=qr_image)

root = tk.Tk()
input = tk.Entry(root)
qr_image = tk.PhotoImage()
qr_label = tk.Label(root, image=qr_image, width=300, height=300)
button = tk.Button(root, text="Generate code", command=GenerateQRCode)

input.pack(side="top", fill="x")
qr_label.pack(side="top")
button.pack(side="bottom")

root.mainloop()

Upvotes: 2

Related Questions