I am trying to create a really simple HMI, to display different images and name of the file and other information in a lower bar using tkinter. I have created a layout, added the background image but the lower rectangle is not visible.
The background image overlays the rectangle, how can I force the ground image to behind all the other components inside the canvas? The black rectangle should be visible at the lower section of the picture
from PIL import Image, ImageTk
from tkinter import Tk, BOTH, Canvas
from tkinter.ttk import Frame, Label, Style
root = Tk()
root.title('Screen')
w = Canvas(root, width=800 , height=480)
w.pack()
back_ground = ImageTk.PhotoImage(Image.open("./icon/sync_background.bmp"))
back_ground_label = Label(image=back_ground, borderwidth=0)
back_ground_label.place(x=0,y=0)
w.create_rectangle(0, 400, 800, 480,outline="#000", fill="#000")
w.pack()
root.mainloop()
Your background image is placed on top of the canvas and so it hides the canvas. You should create the image using w.create_image(...) instead:
from PIL import Image, ImageTk
from tkinter import Tk, BOTH, Canvas
root = Tk()
root.title('Screen')
back_ground = ImageTk.PhotoImage(Image.open("./icon/sync_background.bmp"))
w = Canvas(root, width=800 , height=480)
w.pack()
w.create_image(0, 0, image=back_ground, anchor='nw')
w.create_rectangle(0, 400, 800, 480,outline="#000", fill="#000")
root.mainloop()
Here is what you can do:
from PIL import Image, ImageTk
from tkinter import Tk, BOTH, Canvas
from tkinter.ttk import Frame, Label, Style
root = Tk()
root.title('Screen')
w = Canvas(root, width=800 , height=480)
w.pack()
back_ground = ImageTk.PhotoImage(Image.open("./icon/sync_background.bmp"))
back_ground_label = Label(image=back_ground, borderwidth=0)
back_ground_label.place(x=0,y=0)
rect = w.create_rectangle(0, 400, 800, 480,outline="#000", fill="#000")
w.tag_raise(rect)
w.pack()
root.mainloop()
What this does is creates an object "rect" and then uses the tag_raise method on it to bring it in front.
Hope it helps!
Cheers!
Related
I'm making a hangman-like game; for that, I need all the different stages of the man to be visualized, hence images. I want the entire tkinter window to be an image, when I change the size it pushes the image right.
from tkinter import *
root=Tk()
root.geometry("600x350")
canvas = Canvas(root, width=1600, height=900)
canvas.pack()
img = PhotoImage(file="4.png")
canvas.create_image(470,190, image=img, )
root.mainloop()
If canvas is bigger than window then when you resize then it show more canvas but and it can looks like it moves image.
But if you use smaller canvas then pack() will try to keep centered horizontally. And if you add pack(expand=True) then it will try to keep it centered vertically.
In example code I added red background to window to show where is canvas
import tkinter as tk # PEP8: import *
root = tk.Tk()
root.geometry("600x350")
root['bg'] = 'red'
img = tk.PhotoImage(file="lenna.png")
canvas = tk.Canvas(root, width=600, height=350)
canvas.pack(expand=True)
canvas.create_image(300, 175, image=img)
root.mainloop()
Image Lenna from Wikipedia
PEP 8 -- Style Guide for Python Code
Before resizing:
After resizing:
If you want to draw only image then you could use Label(image=img)
import tkinter as tk # PEP8: import *
root = tk.Tk()
root.geometry("600x350")
root['bg'] = 'red'
img = tk.PhotoImage(file="lenna.png")
label = tk.Label(root, image=img)
label.pack(expand=True)
root.mainloop()
Before resizing:
After resizing:
BTW:
tkinter can bind() some function to event <Configure> and it will execute this function everytime when you resize window (and/or move window) - and this function may also move or resize image in window.
import tkinter as tk # PEP8: import *
from PIL import Image, ImageTk
def resize(event):
global img
lower = min(event.width, event.height)
#print(event.width, event.height, 'lower:', lower)
new_image = original_image.resize((lower, lower))
img = ImageTk.PhotoImage(new_image) # need to assign to global variable because there is bug in PhotoImage
label['image'] = img
# --- main ---
root = tk.Tk()
root.geometry("350x350")
root['bg'] = 'red'
original_image = Image.open("lenna.png")
img = ImageTk.PhotoImage(original_image)
label = tk.Label(root, image=img)
label.pack(expand=True)
root.bind('<Configure>', resize)
root.mainloop()
Before (it resized image at start to fit window):
After (it resized image to fit window):
I have a code that is working perfectly but it's not giving me transparent background, (here is the image ) after a research on web, I found the solution by using canvas widget, we can us images with transparent background.
Here is my code,
import tkinter as tk
from PIL import Image, ImageTk
def work(progress=1):
if progress > 300: # define the width by yourself
return
tmp_images = ImageTk.PhotoImage(progress_images.resize((progress, 10))) # the image size
lb.image = tmp_images # keep reference
lb["image"] = tmp_images # change the image
root.add = root.after(100, work, progress+10) # define the amplitude by yourself
root = tk.Tk()
progress_images = Image.open("path.png")
lb = tk.Label(root, bg="black")
lb.pack(side="left")
work()
root.mainloop()
but I am confused how to change Label widget into Canvas ? can anyone help me please ? I am noob in Tkinter still!!!
You can use canvas.create_text(...) to replace the labels and then use canvas.itemconfig(...) to update the labels. I got this from an other stack over flow question
reference link :-
add label ..
Below is a modified code using Canvas:
import tkinter as tk
from PIL import Image, ImageTk
def work(progress=10):
if progress > 300: # define the width by yourself
return
canvas.image = ImageTk.PhotoImage(progress_images.resize((progress, 30))) # the image size
canvas.itemconfig(pbar, image=canvas.image) # update image item
root.add = root.after(100, work, progress+10) # define the amplitude by yourself
root = tk.Tk()
progress_images = Image.open("path.png")
canvas = tk.Canvas(root, width=300, height=30, bg='black', highlightthickness=0)
canvas.pack()
pbar = canvas.create_image(0, 0, anchor='nw') # create an image item
work()
root.mainloop()
hope you're all doing well. I've got a problem I hope you can help with.
I'm trying to build a board game in tkinter. This will have different shaped tiles being placed in squares on top of a background image. I have managed to add in the background with tk.PhotoImage and tk.Label, and correctly resized the image of the tile with ImageTk.PhotoImage.
However, when I place the tile on the board, all transparency is lost and replaced with monotone grey.
Minimal Code:
from PIL import Image,ImageTk
import tkinter as tk
def tile_push():
pass
# Create background image
root = tk.Tk()
root.geometry("390x500") # Size of background board
background_image = tk.PhotoImage(file="Gameboard.png")
background_label = tk.Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
# Create button
im = Image.open("Chick.png").resize((100,100))
image_player_1 = ImageTk.PhotoImage(im)
b = tk.Button(root, image=image_player_1, command=tile_push, borderwidth=0, highlightthickness=0)
b.place(x=140, y=258, width=115, height=115)
tk.mainloop()
A similar question on SO shows how to set the background as black, but I need the background to be transparent.
Any help will be greatly appreciated!
Thanks for the support acw, I've managed to get it going now. This is what I did:
from PIL import Image,ImageTk
import tkinter as tk
def tile_push(*args, **kwargs):
print("It's alive!")
# Create background image
root = tk.Tk()
root.geometry("390x500") # Size of background board
canvas = tk.Canvas(root, width=390, height=500)
canvas.place(x=0,y=0)
background_image = tk.PhotoImage(file="Gameboard.png")
canvas.create_image((0,0), anchor="nw", image=background_image)
# Create button
im = Image.open("Chick.png").resize((115,115))
imTk = ImageTk.PhotoImage(im)
chick = canvas.create_image((140,258), anchor="nw", image=imTk)
canvas.tag_bind(chick, '<Button-1>', tile_push)
tk.mainloop()
I have a program and I want when someone clicks a button, the canvas image will change. My code is below:
from PIL import ImageTk,Image, ImageFont, ImageDraw
import tkinter
import textwrap
from tkinter import Frame, Canvas, Text, INSERT, END
root = tkinter.Tk()
root.geometry("296x337")
root.resizable(False, False)
im=Image.open("red.jpg")
photo=ImageTk.PhotoImage(im)
cv = tkinter.Canvas()
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(0, 0, image=photo, anchor='nw')
def changepic():
###place where I want to change the Canvas Image
print("change color")#I added this because python wouldn't let me run thee function without something.
a2=tkinter.Button(root,text='change color',bd=0, command=changepic)
a2.config(highlightbackground='black')
a2.place(x=135, y=70)
Instead of using Canvas, I replaced the code so that it prints the image using tkinter.Label:
from PIL import ImageTk,Image, ImageFont, ImageDraw
import tkinter
import textwrap
from tkinter import Frame, Canvas, Text, INSERT, END
root = tkinter.Tk()
root.geometry("296x337")
root.resizable(False, False)
img = ImageTk.PhotoImage(Image.open("red.jpg"))
panel = tkinter.Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
def changepic(imagename):
img2 = ImageTk.PhotoImage(Image.open(imagename))
panel.configure(image=img2)
panel.image = img2
a2=tkinter.Button(root,text='change color',bd=0, command=changepic("blue.jpg")
a2.config(highlightbackground='black')
a2.place(x=135, y=70)
I got my information from: How to update the image of a Tkinter Label widget?
And: https://www.tutorialspoint.com/python/tk_label.htm
I am working on a game project for school, which look like this : In-game aspect
I have created these colored polygons like this :
ship = can.create_polygon(410,650,450,600,490,650 , fill= 'red' , outline='black')
ennemies = can.create_rectangle(x-r, y-r, x+r, y+r, fill='green')
So now i want to fill them with my own image. Is that possible ? And how ?
try:
import tkinter as tk
from tkinter.constants import *
except ImportError: # Python 2.x
import Tkinter as tk
from Tkconstants import *
# Create the canvas, size in pixels.
canvas = tk.Canvas(width=300, height=200, bg='black')
# Pack the canvas into the Frame.
canvas.pack(expand=YES, fill=BOTH)
# Load the .gif image file.
gif1 = tk.PhotoImage(file='small_globe.gif')
# Put gif image on canvas.
# Pic's upper-left corner (NW) on the canvas is at x=50 y=10.
canvas.create_image(50, 10, image=gif1, anchor=NW)
# Run it...
tk.mainloop()