I am working on a project with a simple GUI based on Tkinter. I want to have a background image for the window (which shall have eventually more widgets on it). As you can think, the background image should be placed at the very borders of the window (on position x=1,y=1), but I can't find any solutions on the web for this - or how to place an image anywhere but the "default" position: it is always displayed in the center, or if there are other widgets, below them.
Here's the relevant excerpt of my code:
class tkGUI():
WIN_WIDTH = 640
WIN_HEIGHT = 480
WIN_MAXWIDTH = WIN_WIDTH + 160
WIN_MAXHEIGHT = WIN_HEIGHT + 120
# /*main window*/
root = tk.Tk()
root.title(program.title)
root.config(background="gray")
root.minsize(WIN_WIDTH, WIN_HEIGHT)
root.maxsize(WIN_MAXWIDTH, WIN_MAXHEIGHT)
#/*root.geometry("300x300")*/
#/* btw: adding this frame makes the image being displayed far below, mostly outside the window */
#frame = tk.Frame(root, width=WIN_WIDTH, height=WIN_HEIGHT)
#frame.pack(padx=10, pady=10)
#/* label widget (which also "pushes" the image down)*/
tk.Label(root, text=program.name).pack()
tk.Label(root, text=program.subtitle).pack()
IMG_BG = tk.PhotoImage(file="./data/stmod_graybg_s.png")
tk.Label(root, image=IMG_BG).pack()
Is there a way to render the image on a certain position (and make it stay there despite other widgets)? Or is there a way to define it as a real "background image" that stays below everything else?
The pack()
geometry manager, which you're using, arranges widgets in a sequential manner. That's why the image is being pushed down by your labels.
You can use the place()
geometry manager. The "background" must be placed before any other widgets that you want to appear on top of it.
# Background Image
self.IMG_BG = tk.PhotoImage(file="./data/stmod_graybg_s.png")
self.bg_label = tk.Label(self.root, image=self.IMG_BG)
self.bg_label.place(x=0, y=0, relwidth=1, relheight=1)
You can also use the Canvas
widget but for simple background images place()
is a straightforward and efficient choice.