As in question is it possible to upload a photo and make it relative?
I am trying to upload an image to my GUI, but it is not relative, so when you maximalize window, then unfortunatelly there is a problem with its size.
I want to change the image size dynamically when the window is resizing
Some example code:
import tkinter as tk
from PIL import ImageTk, Image
HEIGHT, WIDTH = 640, 700
root = tk.Tk()
canvas0 = tk.Canvas(height=HEIGHT, width=WIDTH)
canvas0.pack()
canvas = tk.Canvas(bg='black')
canvas.place(relx=0, rely=0, relheight=1, relwidth=1)
frame = tk.Frame(canvas, bg='#009900')
frame.place(relx=0.12, y=2, rely=0, relwidth=0.75, relheight=1)
column_1_img = Image.open('column.png')
column_1_img = ImageTk.PhotoImage(column_1_img)
column_label_1 = tk.Label(canvas, image=column_1_img)
column_label_1.image = column_1_img
column_label_1.place(relheight=1, relwidth=0.2)
root.mainloop()
This code produces this output:
Not fullscreen
Fullscreen
I want an image to automatically adjust to the label size, so do you have some ideas how?
Bind the <Configure> to an event handler and use the PIL's resize method to resize the image.
Here is an example:
import tkinter as tk
from PIL import ImageTk, Image
def resize_image(event):
column_label_1.resized = ImageTk.PhotoImage(column_1_img.resize((event.width, event.height), resample = Image.NEAREST))
column_label_1['image'] = column_label_1.resized
HEIGHT, WIDTH = 640, 700
root = tk.Tk()
canvas0 = tk.Canvas(height=HEIGHT, width=WIDTH)
canvas0.pack()
canvas = tk.Canvas(bg='black')
canvas.place(relx=0, rely=0, relheight=1, relwidth=1)
frame = tk.Frame(canvas, bg='#009900')
frame.place(relx=0.12, y=2, rely=0, relwidth=0.75, relheight=1)
column_1_img = Image.open(r'img_path')
column_img = ImageTk.PhotoImage(column_1_img)
column_label_1 = tk.Label(canvas, image=column_img)
column_label_1.image = column_1_img
column_label_1.place(relheight=1, relwidth=0.2)
column_label_1.bind('<Configure>', resize_image)
root.mainloop()
Related
I am fairly new to tkinter and I've been working on this feature of my project that allows a user to drag and drop canvas objects around, however when I move around the canvas and try to move the canvas object again, it behaves weirdly. It's somewhat hard to explain so I left a video below for context and the code as well. Any kind of help is appreciated :)
import customtkinter
from tkinter import Canvas
from PIL import Image, ImageTk
def move(event):
my_canvas.moveto(my_image,event.x-50,event.y-50)
def scan(event):
my_canvas.scan_mark(event.x, event.y)
def drag(event):
my_canvas.scan_dragto(event.x, event.y, gain=2)
def display_coords(event):
my_label.configure(text=f"X: {event.x} Y:{event.y}")
app = customtkinter.CTk()
frame1 = customtkinter.CTkFrame(master=app)
frame1.pack(padx=10,pady=10, expand=True, fill="both")
my_canvas = Canvas(master=frame1, height=100, width=100, bg="black")
my_canvas.pack(expand=True, fill="both")
#Resize image(originally 512 x 512)
img = Image.open("assets/computadora.png")
resized_image = img.resize((100,100))
image = ImageTk.PhotoImage(resized_image)
frame1.image = image
my_image = my_canvas.create_image(0, 0, image=image, anchor="nw")
my_canvas.tag_bind(my_image,"<Button1-Motion>", move, add="+")
my_canvas.bind("<Button-3>", scan)
my_canvas.bind("<Button3-Motion>", drag)
#Provides X-Y coordinates of mouse cursor when canvas object is selected
my_label = customtkinter.CTkLabel(master=my_canvas, text="X: None Y: None")
my_label.pack(padx="10px", pady="10px", anchor="se")
my_canvas.tag_bind(my_image, "<Button1-Motion>", display_coords, add="+")
my_canvas.configure(scrollregion=my_canvas.bbox(my_image))
app.mainloop()
here
I am using Tkinter, I want to clear the canvas using a button(close_button) but the camera is always on and the button not doing anything I want the button to close the camera feed and reset the canvas so that the canvas becomes as it was before I opened the cam
from tkinter import*
import tkinter as tk
from PIL import Image, ImageTk
import cv2
# new window function which will be called when button pressed
class OpenCam():
def __init__(self, window, cap):
self.window = window
self.cap = cap
self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.interval = 20 # Interval in ms to get the latest frame
# Create canvas for image
self.canvas = tk.Canvas(self.window, width=self.width, height=self.height)
self.canvas.place(x=100,y=100)
# close Button need to close cam and reset canvas
close_button = tk.Button(root, text="close", bg='black', fg='white', command=self.canvas.delete() )
close_button.place(x=610,y=0)
# Update image on canvas
self.update_image()
def update_image(self):
# Get the latest frame and convert image format
self.image = cv2.cvtColor(self.cap.read()[1], cv2.COLOR_BGR2RGB) # to RGB
self.image = Image.fromarray(self.image) # to PIL format
self.image = ImageTk.PhotoImage(self.image) # to ImageTk format
# Update image
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.image)
# Repeat every 'interval' ms
self.window.after(self.interval, self.update_image)
def new_window():
OpenCam(root, cv2.VideoCapture(0))
#create original window
root = tk.Tk()
root.title("ADD CAM: ")
canvas = tk.Canvas(root, height=1000, width=1000)
canvas.pack()
#create button that will be placed
button = tk.Button(root, text="ADD CAM", bg='black', fg='white', command=new_window )
button.place(x=0,y=0)
root.mainloop()
Suppose I have 'n' image files in a directory filedir which I want to view via tkinter console. Now, I want to skip a few files whenever necessary, using a button click event which invokes a function nextFile().
E.g.
import os
def nextFile():
global img
img_2 = process(img)
return img_2
window = tk.Tk()
window.title("File Viewer")
files = os.listdir(filedir)
button1 = tk.Button(window, text="Browse Files...", fg="black", command=askopenfilename)
button2 = tk.Button(window, text="SELECT", width=50, command=nextFile)
canvas = tk.Canvas(window, width=width, height=height)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.BOTTOM)
canvas.pack()
for f in files:
img = cv2.cvtColor(cv2.imread(filedir + '/' + f), cv2.COLOR_BGR2RGB)
photo = ImageTk.PhotoImage(image=Image.fromarray((img))
canvas.create_image(0, 0, image=photo, anchor=tk.CENTER)
window.mainloop()
Any help is appreciated. Thanks!
Here is a simple example using PIL to load the inital image and then use a button and function to load each next image.
import tkinter as tk
from PIL import ImageTk, Image
import os
path = 'C:/your/file/path/here'
def nextFile():
# the global is needed to keep track of current index and also keep
# a reference of the image being displayed so its is not garbage collected.
global current_ndex, image
current_ndex += 1
if current_ndex < len(files):
img = Image.open('{}/{}'.format(path, files[current_ndex]))
image = ImageTk.PhotoImage(img)
# clear the canvas before adding the new image.
canvas.delete("all")
canvas.create_image(0, 0, image=image, anchor=tk.CENTER)
my_window = tk.Tk()
my_window.title("File Viewer")
files = os.listdir(path)
current_ndex = 0
button2 = tk.Button(my_window, text="Next", width=50, command=nextFile)
canvas = tk.Canvas(my_window, width=100, height=100)
button2.pack(side=tk.BOTTOM)
canvas.pack()
first_image = files[0]
img = Image.open('{}/{}'.format(path, first_image))
image = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, image=image, anchor=tk.CENTER)
my_window.mainloop()
I need to resize my window(tkinter) according to the width and height of my background image.
My code
from tkinter import *
from PIL import ImageTk
import cv2
image=cv2.imread("New_refImg.png")
width_1, height_1,channels = image.shape
canvas = Canvas(width = width_1, height = height_1, bg = 'blue')
canvas.pack(expand = YES, fill = BOTH)
img = ImageTk.PhotoImage(file = "New_refImg.png")
canvas.create_image(10, 10, image = img, anchor = NW)
mainloop()
I'm using a simple method, I call the same image twice : image=cv2.imread("New_refImg.png") and img = ImageTk.PhotoImage(file = "New_refImg.png") but is there a way change this line img = ImageTk.PhotoImage(file = "New_refImg.png") to something like that img = ImageTk.PhotoImage(image) (image already has been called in the 3rd line of the code)
Thank you
I don't know about PIL, but I can show you how to do it in tkinter:
from tkinter import *
root = Tk() # Create Tk before you can create an image
img = PhotoImage(file='pilner.png')
w, h = img.width(), img.height()
canvas = Canvas(root, width=w, height=h, bg='blue', highlightthickness=0)
canvas.pack(expand = YES, fill = BOTH)
canvas.create_image(0, 0, image=img, anchor=NW)
root.mainloop()
highlightthickness=0 rmoves the highlight border on the canvas. I'm positioning it at 0,0 so as to not show the bg.
I am trying to create a simple game using tkinter in python 3.5 using the canvas widget. For this game I am need to be able to use a transparent (png) image. Here is my code:
from PIL import ImageTk
from tkinter import Tk, Canvas
root = Tk()
im = ImageTk.PhotoImage(file="test.png")
canvas = Canvas(root, width=900, height=900)
canvas.pack()
canvasImage = canvas.create_image(0, 0, image=im, anchor="nw")
root.mainloop()
The problem is that, despite getting no errors i can't load an image with a transparent background but i can load png images with no transparent background.
You should try this:
from tkinter import *
root = Tk()
canvas = Canvas(root, width=500, height=500)
canvas.pack()
img = PhotoImage(file='path/your_image.png')
canvas.create_image(250, 250, image=img)
root.mainloop()
Output here