简体   繁体   English

如何使用Tkinter更新图片?

[英]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.我一直在使用 Tkinter 更新 python 中的图片时遇到问题。该程序正在创建 QR 码并将其显示在 window 上。我不知道如何在它更改时更新它,文件名保持不变只是改变。 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.它负责创建 QR 码并显示它,但是,就像我说的,不知道如何在文件名保持不变的情况下更新它。 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.我可以制作 qrcode1.png,然后如果需要新的二维码,检查它是否存在,如果存在,删除它并制作 qrcode2.png 并显示它,反之亦然。 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.谢谢你。

You should create the label with the qr code once, and then update the label whenever you create the new qr code.您应该使用二维码创建一次 label,然后在创建新二维码时更新 label。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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