Home > database >  Adding image to the background of UI
Adding image to the background of UI

Time:06-21

I wanted to add image to the background of the window but failed to do that... I tried tk.Canvas after some googling but didn't work..I was expecting all the widgets on that image

import rotors;import tkinter as tk;from tkinter import HORIZONTAL;import tkinter.messagebox as mbx;import pyperclip
class UI():    
    def __init__(self, window, encryption):
        self.encryption = encryption
        self.window = window
        self.window.title('Security Window')
        self.window.minsize(width = 500, height = 200)
        self.x = tk.StringVar() 

I tried a lot to add the background image to the UI but failed Canvas and Label were few options that I had tried. enter image description here

Any background image is fine for me but need to know how can I do that..

CodePudding user response:

Modify your init method, in your UI class, to add self.bg and self.back_ground:

[...]
class UI(): 
    def __init__(self, window, encryption):
        self.encryption = encryption
        self.window = window
        self.window.title('Security Window')
        self.window.minsize(width = 500, height = 200)
        self.bg = tk.PhotoImage(file = "green.png")
        self.back_ground = tk.Label(image=self.bg)
        self.back_ground.place(x = 0,y = 0)
        self.x = tk.StringVar() 
[...]

(Image can be downloaded here : https://fr.m.wikipedia.org/wiki/Fichier:Solid_green.png)

EDIT: If you wanna resize the image to fill all the background, you can use the PILLOW lib:

from PIL import Image

img = Image.open("green.png")
img = img.resize((500, 200), Image.ANTIALIAS)

So it would give something like this:

[...]
class UI():    
    def __init__(self, window, encryption):
        self.encryption = encryption
        self.window = window
        self.window.title('Security Window')
        self.window.minsize(width = 500, height = 200)
        img = Image.open("green.png")
        img = img.resize((1000, 400), Image.ANTIALIAS)
        img.save('green_resized.png')
        self.bg = tk.PhotoImage(file = "green_resized.png")
        self.back_ground = tk.Label(image=self.bg)
        self.back_ground.place(x = 0,y = 0)
        self.x = tk.StringVar()
[...]
  • Related