asteia apo seires
asteia apo seires

Reputation: 11

Tkinter images and geometry creation

I've tried to do a star fractal drawing a star using tkinter and putting an image as a background.

from tkinter import *
from PIL import ImageTk, Image  
import tkinter as tk

app = Tk()
app.title("Welcome")
img =Image.open('C:\\Users\\Stefa\\Downloads\\galaxy.jpeg')
bg = ImageTk.PhotoImage(img)
canvas_width=800
canvas_height=800
master = tk.Tk()

label = Label(app, image=bg)
label.place(x = 0,y = 0)
label2 = Label(app, text = "WELCOME TO OUR GALAXY",
               font=("Times New Roman", 24))

label2.pack(pady = 50)
app.geometry(f"{canvas_width}x{canvas_height}")
can_widgt=Canvas(app, width=canvas_width, height= canvas_height)
can_widgt.pack()

points=[200,20,80,396,380,156,20,156,320,396]
can_widgt.create_polygon(points, outline='red',fill='cyan', width=6)

app.mainloop()

That's the code

However when i run it i want the star to be upon the background image. Any solutions for this ? Thanks

Upvotes: 1

Views: 277

Answers (2)

cdlane
cdlane

Reputation: 41905

You're specifically missing the line of code that @BryanOakley provides (+1) but in general you have too much redundant code (e.g. two roots, two different geomentry managers):

import tkinter as tk
from PIL import ImageTk, Image

canvas_width = 800
canvas_height = 800

root = tk.Tk()
root.title("Welcome")

img = Image.open(r'C:\Users\Stefa\Downloads\galaxy.jpeg')
bg = ImageTk.PhotoImage(img)

label = tk.Label(root, text="WELCOME TO OUR GALAXY", font=("Times New Roman", 24))
label.pack(pady=50)

can_widgt = tk.Canvas(root, width=canvas_width, height=canvas_height)
can_widgt.pack()

can_widgt.create_image(0, 0, anchor="nw", image=bg)

points = [200, 20, 80, 396, 380, 156, 20, 156, 320, 396]
can_widgt.create_polygon(points, outline='red', fill='cyan', width=6)

root.mainloop()

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 386325

You need to create the image as a canvas object rather than as a label.

For example, this add the image to the top-left corner of the canvas, with the drawing on top of it:

can_widgt.create_image(0, 0, anchor="nw", image=bg)

Upvotes: 1

Related Questions