I am able to flip an image on the canvas. I am doing it by saving it in a file by using ImageGrab function and rotating that by using ImageOps and placing that on canvas but when the image is edited I mean when objects are rotated or dragged am not able to flip. The drag and rotate part is not there in code.It would be too long if I include it.
Here is my code
from tkinter import *
from PIL import ImageTk,Image,ImageGrab
import PIL
from tkinter import filedialog
from PIL import ImageOps
root = Tk()
def selected1(event):
if clicked1.get()=="flip horizontal":
x2=root.winfo_rootx()+canvas.winfo_x()
y2=root.winfo_rooty()+canvas.winfo_y()
x1=x2+root.winfo_screenwidth()
y1=y2+root.winfo_screenheight()
print("save")
ImageGrab.grab().crop((x2,y2,x1,y1)).save("saver.jpg")
im = Image.open("saver.jpg")
im = ImageOps.mirror(im)
im.save("saver2.jpg")
canvas.delete('all')
global img1
img1=Image.open("saver2.jpg")
img1=img1.resize((1225,685),Image.ANTIALIAS)
canvas.img=ImageTk.PhotoImage(img1)
canvas_img=canvas.create_image(0,0,image=canvas.img,anchor="nw")
if clicked1.get()=="flip vertical":
x2=root.winfo_rootx()+canvas.winfo_x()
y2=root.winfo_rooty()+canvas.winfo_y()
x1=x2+root.winfo_screenwidth()
y1=y2+root.winfo_screenheight()
print("save")
ImageGrab.grab().crop((x2,y2,x1,y1)).save("saver.jpg")
im = Image.open("saver.jpg")
im = ImageOps.flip(im)
im.save("saver1.jpg")
canvas.delete('all')
global img2
img2=Image.open("saver1.jpg")
img2=img2.resize((1225,685),Image.ANTIALIAS)
canvas.img=ImageTk.PhotoImage(img2)
canvas_img=canvas.create_image(0,0,image=canvas.img,anchor="nw")
def selected2(event):
if clicked2.get()=="open file":
global img
root.filename=filedialog.askopenfilename(initialdir="/ROBIN",title="select a file",filetypes=(("image files","*.jpg"),("all files","*.*")))
img=Image.open(root.filename)
img=img.resize((1225,685),Image.ANTIALIAS)
canvas.img=ImageTk.PhotoImage(img)
canvas_img=canvas.create_image(0,0,image=canvas.img,anchor="nw")
if clicked2.get()=="save file":
x2=root.winfo_rootx()+canvas.winfo_x()
y2=root.winfo_rooty()+canvas.winfo_y()
x1=x2+root.winfo_screenwidth()
y1=y2+root.winfo_screenheight()
print("save")
ImageGrab.grab().crop((x2,y2,x1,y1)).save("checker.jpg")
if clicked2.get()=="exit":
root.quit()
canvas = Canvas(root)
canvas.pack(fill=BOTH, expand=1)
rectangles=[]
canvas.grid(column=0, row=0, sticky=(N,W,E,S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
options1=[
"select flip",
"flip horizontal",
"flip vertical",
]
clicked1=StringVar()
clicked1.set("select flip")
drop1=OptionMenu(root,clicked1,*options1,command=selected1)
drop1.place(relx=1,x=-1,y=1,anchor=NE)
clicked2=StringVar()
clicked2.set("select")
options2=[
"select",
"open file",
"save file",
"exit",
]
drop2=OptionMenu(root,clicked2,*options2,command=selected2)
drop2.place(relx=1,x=-1,y=40,anchor=NE)
root.mainloop()
Related
I'm working on a python project that takes an image that the user selects and removes a certain color from it, I'm trying to display the selected image along with a button that takes you to the selection menu on the file explorer on the user's computer, the button works just fine, but the image is not being displayed at all. any help would be appreciated.
the code:
#import
from PIL import Image, ImageTk
from fileinput import filename
import tkinter as tk
from tkinter import filedialog
from tkinter import *
root = Tk()
root.geometry("750x500")
root.title("Shibly Letter Head")
canvas = Canvas(root, width = 500, height = 500)
canvas.pack()
#uploaded info
def UploadAction(event=None):
from PIL import Image
filename = filedialog.askopenfilename()
print('Selected:', filename)
img = Image.open(filename)
img.show()
image_data = img.load()
height,width = img.size
for loop1 in range(height):
for loop2 in range(width):
r,g,b = image_data[loop1,loop2]
image_data[loop1,loop2] = 0,g,b
img.save('changed.jpeg')
#display image
canvas.create_image(10,
10,
anchor=NW,
image= filename
)
#button
button = tk.Button(root, text='Open', height=5, width=45, command=UploadAction)
button.place(x=220, y=419)
root.mainloop()
PS, apologies if this is a dumb question but I'm still a beginner and couldn't fix this problem myself.
I am trying to create a button that will clear a canvas and then put an image in the canvas selected from a Tkinter file dialog. I am using the canvas.delete("all") method shared here to try clearing the canvas before selecting a new image, but the new image is appearing above the existing image rather than replacing it.
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
from PIL import Image, ImageTk
root = Tk()
canvas1 = Canvas(root, width=500, height=500)
canvas1.pack()
class widgets:
def __init__(self, parent):
self.myParent = parent
self.myContainer1 = Frame(parent)
self.myContainer1.pack()
self.button1 = Button(self.myContainer1, command=self.button1click)
self.button1.config(text="Select Image")
self.button1.pack(side=TOP)
def button1click(self):
canvas1.delete("all")
path = tkFileDialog.askopenfilename(filetypes=[("Image File", '.png')])
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
imglabel = Label(canvas1, image=tkimage)
imglabel.image = tkimage
imglabel.pack()
widgets = widgets(root)
root.mainloop()
I would like to open the filedialog after pressing a button. Then I could choose an image and display it on a canvas. (My goal is to do a very simple image editor) Unfortunately, the filedialog open up automatically when I start the program. Is there a way for example to do something like this:
press a button to open the filedialog
choose an image
display the image on the canvas
Here is my code that I've done so far
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
root = Tk()
#function to select my image by using the filedialog
def select_image():
file_path = filedialog.askopenfilename()
return Image.open(file_path)
#button to press to open filedialog
select = Button(root, text="select an image", command=select_image)
select.pack()
#the canvas where the image will be display
canvas = Canvas(root, width= 400, height=400, bg="grey")
canvas.pack()
image_tk = ImageTk.PhotoImage(select_image())
canvas.create_image(200,200, image= image_tk)
root.mainloop()
The filedialog opens because of this line:
image_tk = ImageTk.PhotoImage(select_image())
My Solution is:
from tkinter import Tk, filedialog, Frame, Button, Canvas
from PIL import Image, ImageTk
class Gui:
def __init__(self, master):
self.master = master
self.create_widgets()
def create_widgets(self):
self.select = Button(self.master, text="select an image", command=self.select_image)
self.select.pack()
self.canvas = Canvas(self.master, width= 400, height=400, bg="grey")
self.canvas.pack()
def select_image(self):
file_path = filedialog.askopenfilename()
des = Image.open(file_path)
bg_image = ImageTk.PhotoImage(des)
self.canvas.bg_image = bg_image
self.canvas.create_image(200,200, image=self.canvas.bg_image)
if __name__ == "__main__":
root = Tk()
my_gui = Gui(root)
root.mainloop()
I'm trying to write a script that will allow the user to select a folder with images and then save the coordinates of the user's clicks on each image. To do this I would like to display each image file on a Tkinter canvas, save click locations, then when the canvas is closed, open the next image.
I can get this to work for a single image with the code below (adapted from this question). I was hoping the for File in imgs loop would keep opening the next image, but it does not. I suspect I need a on_closing function to tell Tkinter to open another image.
What's the proper way to have Tkinter open the next image after closing an image?
from Tkinter import *
from tkFileDialog import askopenfilenames, askopenfilename, askdirectory
from PIL import Image, ImageTk
import cv2
import numpy as np
import os
if __name__ == "__main__":
root = Tk()
#setting up a tkinter canvas with scrollbars
frame = Frame(width=1920, height=1080, bd=2, relief=SUNKEN)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
xscroll = Scrollbar(frame, orient=HORIZONTAL)
xscroll.grid(row=1, column=0, sticky=E+W)
yscroll = Scrollbar(frame)
yscroll.grid(row=0, column=1, sticky=N+S)
canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)
canvas.config(width=1920, height=1080)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
xscroll.config(command=canvas.xview)
yscroll.config(command=canvas.yview)
frame.pack(fill=BOTH,expand=1)
# Function to be called when mouse is clicked
def save_coords(event):
coords.append([event.x, event.y])
# def on_closing():
# Open the next image file
# Create empty list for coordinate arrays to be appended to
coords = []
# Choose multiple images
img_dir = askdirectory(parent=root, initialdir="D:/Temp/", title='Choose folder')
os.chdir(img_dir)
imgs = os.listdir(img_dir)
#imgs = askopenfilenames(parent=root, initialdir="D:/Temp/cvCal/", title='Choose images')
for File in imgs:
img = ImageTk.PhotoImage(Image.open(File).resize((1280,720), Image.ANTIALIAS))
canvas.create_image(0,0,image=img,anchor="nw")
canvas.config(scrollregion=canvas.bbox(ALL))
canvas.bind("<Button 1>",save_coords)
# on_closing()...
root.mainloop()
It would be a lot easier if you can use a Label instead:
Also, note there is no reason to use ImageTk since loading an image from a file is built into tkinter as Tkinter.PhotoImage.
Also, I converted your wildcard import to a normal import; wildcard imports are messy and against PEP8.
Lastly, I don't know what you mean with 'on closing', so I added a button to advance to the next image. This will throw a StopIteration error on the last image that you will need to handle.
import Tkinter as tk
from tkFileDialog import askdirectory
import os
# Create empty list for coordinate arrays to be appended to
coords = []
# Function to be called when mouse is clicked
def save_coords(event):
click_loc = [event.x, event.y]
print "you clicked on", click_loc
coords.append(click_loc)
# Function to load the next image into the Label
def next_img():
img_label.img = tk.PhotoImage(file=next(imgs))
img_label.config(image=img_label.img)
root = tk.Tk()
# Choose multiple images
img_dir = askdirectory(parent=root, initialdir="D:/Temp/", title='Choose folder')
os.chdir(img_dir)
imgs = iter(os.listdir(img_dir))
img_label = tk.Label(root)
img_label.pack()
img_label.bind("<Button-1>",save_coords)
btn = tk.Button(root, text='Next image', command=next_img)
btn.pack()
next_img() # load first image
root.mainloop()
print coords
This seems like a pretty straightforward question, but i am having trouble displaying a jpg image when a button is clicked. Here is my code (without the button code for the sake of time):
from tkinter import *
#screen stuff here
canvas = Canvas(app)
canvas.grid(row = 0,column = 0)
photo = PhotoImage(file = "test.jpg")
canvas.create_image(0,0, image = photo)
def show_image():
global canvas
global photo
canvas.create_image(0,0, image = photo)
#button that calls the function down here
Thanks!
This works with Python2:
import Tkinter as tk
import ImageTk
def show_image():
x = canvas.create_image(125, 125, image=tk_img)
while True:
print('show')
canvas.itemconfigure(x, state=tk.NORMAL)
button.configure(text = 'Hide')
yield
print('hide')
canvas.itemconfigure(x, state=tk.HIDDEN)
button.configure(text = 'Show')
yield
root = tk.Tk()
canvas = tk.Canvas(root, width=250, height=250)
canvas.grid(row=0, column=0)
tk_img = ImageTk.PhotoImage(file='image.png')
button = tk.Button(
root, text="Show", command=show_image().next, anchor='w',
width=10, activebackground="#33B5E5")
button.grid(row=1, column=0)
root.mainloop()
In Python3, PhotoImage can open GIF, PPM/PGM images. To open other formats, you may need to install Pillow (a fork of the PIL project for Python3).