How to open and select a file in Python - python

I want to open images in Python by selecting them in a dialog box, how can I do that? I tried tkinter and easygui but when I use them the program freezes and never loads. Any suggestions?

As mentioned in the comments, you should provide a minimal reproducible example. Since you are a new member, I am giving you this example, which can be found here. https://www.geeksforgeeks.org/loading-images-in-tkinter-using-pil/
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
def open_img():
# Select the Imagename from a folder
x = openfilename()
# opens the image
img = Image.open(x)
# resize the image and apply a high-quality down sampling filter
img = img.resize((250, 250), Image.ANTIALIAS)
# PhotoImage class is used to add image to widgets, icons etc
img = ImageTk.PhotoImage(img)
# create a label
panel = Label(root, image=img)
# set the image as img
panel.image = img
panel.grid(row=2)
def openfilename():
# open file dialog box to select image
# The dialogue box has a title "Open"
filename = filedialog.askopenfilename(title='"pen')
return filename
# Create a window
root = Tk()
# Set Title as Image Loader
root.title("Image Loader")
# Set the resolution of window
root.geometry("550x300+300+150")
# Allow Window to be resizable
root.resizable(width=True, height=True)
# Create a button and place it into the window using grid layout
btn = Button(root, text='open image', command=open_img).grid(row=1, columnspan=4)
root.mainloop()

Related

How can I close an image in a tkinter window without closing the window?

I am writing an application that consists of three tkinter windows on the same page: a calendar, a notepad and a 'picture of the day' which is fetched from a bank of images when initiated by the user. The image is named after the calendar date + .jpg. It works fine...the first time. When I select another date and retrieve the image for that date, it comes up behind the first image in the 'picture of the day' window. The problem is that the first image does not disappear when replaced by another. I do not want to close the window, just close the current picture and replace it by the new one. There might a simple way, but I spent hours searching for it. The code below of part of the application. Hopefully, it shows where the problem is. Can you point me in the right direction? Thanks
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import os
photo = Toplevel()
photo.geometry("300x250+1300+150")
photo.resizable(width=True, height=True)
photo.attributes("-topmost", True)
def openfn(): # To go fetch a new image
filename = filedialog.askopenfilename(title='open')
return filename
root.destroy()
def open_img(): # To open a new image
x = openfn()
img = Image.open(x)
img = img.resize((225,200), Image.ANTIALIAS)
im = ImageTk.PhotoImage(img)
panel = Label(photo, image=im)
panel.image = im
panel.pack()
img=img.save(cal.calphoto) # Saves the image (calphoto is date + .jpg)
def retrieve_photo(): # To open an existing image
img=Image.open(cal.calphoto)
im = ImageTk.PhotoImage(img)
panel = Label(photo, image=im)
panel.image = im
panel.pack()
I changed a few things in your code. The main thing is the take the label with the image into the global scope so the function open_img() can make changes to it instead of creating a new label each time it is called. Below open_img() now configures the label to show the image selected each time it is called. (This is basically illustrating what Delrius said.)
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import os
photo = Toplevel()
photo.geometry("300x250+1300+150")
photo.resizable(width=True, height=True)
photo.attributes("-topmost", True)
panel = Label(photo) # panel Label moved into global scope so the
# functions below can access it
def openfn():
filename = filedialog.askopenfilename(title='open')
return filename
root.destroy()
def open_img():
x = openfn()
img = Image.open(x)
img = img.resize((225,200), Image.ANTIALIAS)
im = ImageTk.PhotoImage(img)
panel.config(image=im) # panel label is configured to show image selected
panel.image = im
panel.pack()

IMG2PY for background label and icon in TKINTER

Working in a EXE file with background and Icon embed, I read some ideas about to use img2py in order to create module.py that can be imported into the EXE with pyinstaller.
I successfully create the imagebg.py (BG2.png Background) and imageico.py (ico2.ico Icon) modules using img2py. But there is no example or way to set that images into the modules in the tkinter label as background and the icon into the code.
Please anybody can help me.
Main code where must be imported BG ad ICON modules and use them as background and Icon images for tkinter GUI
#Main code GUI tkinter
import imagebg #from here we must import PNG_File.png for Background
import imageico #from here we must import ICO_File.ico for Icon
import wx #from img2py installation
from tkinter import *
root=Tk()
#set windows size
root.resizable(width=False, height=False)
root.geometry("925x722")
#set title
root.title("SOFT1)")
#frame 1
f1=Frame(root, width=345,height=475,bg="light
grey",highlightbackground="black",highlightthickness=4)
f1.place(x=20,y=235)
#set a image as BG
Logo=PhotoImage(file="PNG_File.png")
lab6=Label(root, image=Logo)
lab6.place(x=0, y=0)
#set a image as ICON
root.iconbitmap("ICO_File.ico")
mainloop()
The module imagebg.py for backgroud generated with IMG2PY
BG2 = PyEmbeddedImage(
b'iVBORw0KGgoAAAANSUhEUgAAAsUAAAKECAIAAABgrdCGAAAACXBIWXMAAA7EAAAOxAGVKw4b'
b'AAAgAElEQVR4nOzdd2Ab5d0H8Oe0hy1vecYjcZw4cfYimwQIEEbYhQJlFgqU3UFZLR2M9i2l'
b'tLRlFcouI5Qww15hZJEdO4kdOx7xtiVrj7v3DwdFlmXppu4kfT9/Wfbdc78YY339TMrpdBIA'
b'AAAAAVRyFwAAAABJD3kCAAAAhEKeAAAAAKGQJwAAAEAo5AkAAAAQCnkCAAAAhEKeAAAAAKGQ'
b'JwAAAEAo5AkAAAAQCnkCAAAAhEKeAAAAAKGQJwAAAEAo5AkAAAAQCnkCAAAAhEKeAAAAAKGQ'
b'JwAAAEAo5AkAAAAQCnkCAAAAhEKeA..... to much characters to be placed in this post
The module imageico.py for icon generated with IMG2PY
from wx.lib.embeddedimage import PyEmbeddedImage
ico2 = PyEmbeddedImage(
b'iVBORw0KGgoAAAANSUhEUgAAAsUAAAKECAYAAADvz0fRAAAABHNCSVQICAgIfAhkiAAAIABJ'
b'REFUeJzs3WeAVNXdBvDnTi/b+7L0svSmIIKd2Gus0ZhiSeKreZOYmGpL15i8SdTEFKMpGkss'
b'GEuMqNFYsCAgHRZYWFiWsn12p7f7fkBwy8zszC1z7537/L7ozs6c82dh4dkz/3OOEAgERBAR'
b'ERERmZhF6wKIiIiIiLTGUExEREREpsdQTERERESmx1BMRERERKbHUExEREREpsdQTERERESm'
b'x1BMRERERKbHUExEREREpsdQTERERESmx1BMRERERKbHUExEREREpsdQTERERESmx1BMRERE'
b'RKbHUExEREREps.... to much characters to be placed in this post
Please any idea of how to use the modules as images for background and icon in the main code GUI Tkinter
You need to convert the wx.Image to PIL compatible image if you want to use it in tkinter application.
Below is an example based on your posted code:
import tkinter as tk
from PIL import Image, ImageTk
import imagebg
import imageico
# function to convert a wx.Image to PIL.ImageTk.PhotoImage
def wx2pil(wx_image):
image = wx_image.Image
w, h = image.GetWidth(), image.GetHeight()
data = image.GetData()
img = Image.frombytes('RGB', (w, h), bytes(data))
return ImageTk.PhotoImage(img)
root = tk.Tk()
root.resizable(False, False)
root.geometry('925x722')
root.title('SOFT1')
# use iconphoto() instead of iconbitmap()
root.iconphoto(False, wx2pil(imageico.ico2))
#set a image as BG
logo = wx2pil(imagebg.BG2)
tk.Label(root, image=logo).place(x=0, y=0)
#frame 1
f1 = tk.Frame(root, width=345, height=475, bg='lightgray', highlightbackground='black', highlightthickness=4)
f1.place(x=20, y=235)
root.mainloop()
Note that I use wxPython v4.1.0.
As it depends on wxPython, why don't you use wxPython for the GUI directly instead of tkinter?

Click to select new image for button - not working

I am trying to create a function for multiple buttons that allows the user to click on a specific button and change the associated image. For now I'm trying to change the image of a single button, but the image doesn't seem to be loaded or recognized for some reason. Any ideas?
import tkinter as tk
from tkinter import simpledialog,filedialog,colorchooser,messagebox,Frame,Button
from PIL import ImageTk, Image
def img_mod():
global btn
ret = filedialog.askopenfilename()
loadn = Image.open(ret)
root.render2 = ImageTk.PhotoImage(loadn)
btn['image'] = loadn
root = tk.Tk()
load1 = Image.open("example.jpg")
root.render1 = ImageTk.PhotoImage(load1)
btn = tk.Button(root, text="My Button", image = root.render1)
btn['command'] = img_mod
btn.pack(fill='both', expand=True)
root.mainloop()
You can run this Python code if you save it with an image titled "example.jpg" in the same folder.

Setting Background image to GUI

I made a GUI with few buttons and I want to change the gray background to an image.
my code looks like this:
from tkinter import *
from urlread import givenumbers # my function
""" Setting The Main GUI """
GUI = Tk()
GUI.title('Check GUI')
GUI.iconbitmap('test.ico')
GUI.geometry("400x400")
background_image=PhotoImage('pic.jpg')
background_label = Label(GUI, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
""" Reading Images For Buttons """
A_Im = PhotoImage(file='A.gif')
""" Creating Buttons """
# A Button
A_Button = Button(GUI, image=A_Im, command=givenumbers)
A_Button.grid(column=0, row=1)
GUI.mainloop()
The code runs without error but the background is still gray without any effect.
The problem is in the line background_image=PhotoImage('pic.jpg'). The PhotoImage class only supports GIF-files, which means that it cannot read the file you're specifying. You should try something like this:
#Python 2.7
import Tkinter as tk
from PIL import Image, ImageTk
window = tk.Tk()
image = Image.open('image.jpg')
photo_image = ImageTk.PhotoImage(image)
label = tk.Label(window, image = photo_image)
label.pack()
# Python 3
import tkinter as tk
from PIL import Image, ImageTk
window = tk.Tk()
image = Image.open('image.jpg')
photo_image = ImageTk.PhotoImage(image)
label = tk.Label(window, image = photo_image)
label.pack()
The Image class from the PIL module supports a variety of formats, among which jpeg and png. You can install the PIL module by running pip install pillow in a command prompt or terminal.
If you want to put the widgets on top of the Label, you could indeed using grid to get them on top of each other, but using a Canvas would probably be easier. You can find more about the Canvas widget here.
This can be done without pil also:
from tkinter import *
import tkinter as ttk
""" Setting The Main GUI """
GUI = Tk()
F1=Frame(GUI)
F1=Frame(GUI,width=400,height=450)
F1.place(height=7000, width=4000, x=100, y=100)
F1.config()
F1.grid(columnspan=10,rowspan=10)
F1.grid_rowconfigure(0,weight=1)
F1.grid_columnconfigure(0,weight=1)
photo=PhotoImage(file="C:\\Users\\HOME\\Desktop\\Eshita\\12th\\computer
\\python\\GUI\\math3.gif")
label = Label(GUI,image = photo)
label.image = photo # keep a reference!
label.grid(row=0,column=0,columnspan=20,rowspan=20)
b=ttk.Button(GUI,text="Start")
b.grid(row=8,column=8)
GUI.mainloop()

empty Tkinter window appears in place of image

I am trying to load images dynamically through browse button to Tkinter window but I am getting the empty window. This is the code of callback function of browse button
supformats = [
('Windows Bitmap','*.bmp'),
('Portable Network Graphics','*.png'),
('JPEG ','*.jpg'),
('CompuServer GIF','*.gif'),
]
filename = askopenfilename(filetypes=supformats)
FILENAME = filename
im=Image.open(FILENAME)
w=im.size[0]
h=im.size[1]
root = Tkinter.Tk()
#canvas = Tkinter.Canvas(root, width=w, height=h)
#canvas.grid(row=0,column=0)
#tk_img = ImageTk.PhotoImage(file = FILENAME)
#canvas.create_image(image=tk_img)
im.show()
root.mainloop()
Thanks in advance for everyone who will help
From effbot's explanation http://effbot.org/tkinterbook/photoimage.htm Note that the file is accessed once only, not twice. This assumes you are using the Python Imaging Library in Tkinter as you did not state what image toolkit is being used.
from PIL import Image, ImageTk
image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)
You can use a PhotoImage instance everywhere Tkinter accepts an image object.
An example:
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

Categories