0

I am working on a Python 3 tkinter app that uses windows with vertical and horizontal (mouse-scrollable) scrollbars along the window's dimensions. But I am unable to display a .png image as the background on the same windows.

I've gone through the methods to add a .png image as the background using a label and canvas but instead of the picture, I can only see white on regions of the window not covered by the frames. Also I find the canvas method really hard as it becomes very difficult to place frames on it which in turn have labels, buttons, scrollbars etc. I've also tried using PIL module but I'm finding trouble importing it from its path (I also don't think it would help much as I'm only trying to use a .png image).

Any suggestions on how to have both the scrollbars and the background image working in the same tkinter window?

#Function to create tkinter window with horizontal and vertical scrollbars

from tkinter import *
from tkinter import ttk
def win():
    r0=Tk()
    r0.title('title')
    f=Frame(r0,bg='BLACK')
    f.pack(fill=BOTH, expand=1)
#Creating canvas for attaching scrollbars
    c=Canvas(f,bg='BLACK')
    c.pack(side=LEFT, fill=BOTH, expand=1)
    s1=ttk.Scrollbar(f, orient=VERTICAL, command=c.yview)
    s2=ttk.Scrollbar(f, orient=HORIZONTAL, command=c.xview)
    s1.pack(side=RIGHT, fill=Y)
    c.configure(yscrollcommand=s1.set)
    s2.pack(side=BOTTOM, fill=X)
    c.configure(xscrollcommand=s1.set)
    c.bind('<Configure>', lambda e:c.configure(scrollregion=c.bbox('all')))
#Function to enable mouse scroll
    def mw(event):
        c.yview_scroll(-1*int((event.delta/120)), 'units')
    c.bind_all('<MouseWheel>', mw)
    r=Frame(c, bg='BLACK')
    c.create_window((0,0),window=r, anchor='s')
    return r, r0
r,r0=win()
#Adding images as background in tkinter window using labels

r=Tk()
# Adjust size 
r.geometry("800x800")
bg=PhotoImage(file="Your_img.png")
# Show image using label
l1 = Label(r, image=bg)
l1.place(x=0, y=0)
#Adding images as background in tkinter window using canvas

r=Tk()
# Adjust size 
r.geometry("800x800")
bg=PhotoImage(file="Your_img.png")
c1=Canvas(r, width=800, height=800)
c1.pack(fill="both", expand=True)
# Display image
c1.create_image(0, 0, image=bg, anchor="nw")
Я J K
  • 1
  • 1
  • The "white regions" is due to this common problem: https://stackoverflow.com/questions/16424091 – Bryan Oakley Sep 28 '21 at 18:59
  • @BryanOakley Thanks! I assumed that it wasn't working due to the presence of an expanding canvas in the window. I added global to the image variable definition in the function and it worked. – Я J K Sep 29 '21 at 11:34

0 Answers0