简体   繁体   中英

How to change tkinter label background image on button click

img= (Image.open("image/frame.png")).resize((240, 240), Image.ANTIALIAS)
new_image = ImageTk.PhotoImage(img)

panel = tk.Label(right_workspace, image=new_image)
panel.pack(side = "top", fill = "none", expand = "none", pady=29)

Thats my label with its image background. Now how can I change this background by a function so everytime my program generates a new qrcode from an input it replaces previous background?

I gather what you're doing, but please leave a minimum reproducible code in future.

Here's an example of how you'd create a functioning tkinter GUI that displays a random image from a list of QR.pngs in a set folder when the button is pressed. You should be able to adapt this to the other part of your program that generates the QR code for you.

import tkinter as tk
from PIL import Image, ImageTk
import os
import random


class QrGenerator:
    def __init__(self, main):
        self.main = main
        self.panel = tk.Label(main)
        self.panel.grid(row=0, column=0)
        self.button = tk.Button(main, text='Random QR', command=self.random_qr)
        self.button.grid(row=1, column=0)

    def random_qr(self):
        fp = r'C:\Filepath\QR Codes Folder'
        os.chdir(fp)
        qr_code = random.choice(os.listdir(fp))
        print(qr_code)
        img = Image.open(qr_code).resize((240, 240), Image.ANTIALIAS)
        new_image = ImageTk.PhotoImage(img)
        self.panel.configure(image=new_image)
        self.panel.image = new_image


if __name__ == '__main__':
    root = tk.Tk()
    gui = QrGenerator(root)
    root.mainloop()

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