Python Versions: 3.7.9
I've tried using Pillow/PIL with show() and close() however that just closes the command prompt and leaves the file viewer still open.
I've tried subprocess Popen but that just gives me the error 'The system cannot find the file specified' even though the file is correct. So I'm just stuck right now. I figured this would've been a simple process for Python.
I'm just trying to open an image and then after the user clicks a button, be able to close it.
Open to suggestions/libraries. Thanks!
Just call this function and a new window will pop up with the image.
Your code wont be executed until the window is closed.
import tkinter
from PIL import ImageTk, Image
def image_preview (path, size = (0, 0)):
root = tkinter.Tk ()#Start window
root.title ("Preview")#Modify this to change the title
rawimg = Image.open(path)#Open image path
if size != (0, 0):#If a specific resolution has been requested
rawimg = rawimg.resize (size)#Change the image resolution
img = ImageTk.PhotoImage(rawimg)#Adapt the image to tkinter
panel = tkinter.Label (root, image = img)#Add image to the window
panel.pack ()#Build window
root.mainloop ()#Run window
Example line to use this:
image_preview ("image.png", (500, 500))#With specified resolution
image_preview ("image.png")#Use the image resolution
Related
I cannot start my Python program. I've a problem that I cannot open a .gif file, and I cannot figure out how!
I keep getting a long error message:
"RuntimeError: Too early to create image"
I have moved the gif files into the same project file as the code, and I tried looking online, but everyone uses different packages, and I just cannot find a way around it. I also have the gifs open on pycharm.
Here is my code:
import random
from tkinter import *
sign = random.randint(0, 1)
if (sign == 1):
photo = PhotoImage(file="X.gif")
else:
photo = PhotoImage(file="O.gif")
My overall goal is to show an image like a finished tic tac toe game, with randomly placed X's and O's, and there does not have to be any specific order like 3 in a row. Here is the homework problem:
Display a frame that contains nine labels. A label may display an image icon for X or an image icon for O, as shown in Figure 12.27c. What to display is randomly decided.
Use the Math.random() method to generate an integer 0 or 1, which corresponds to displaying an X or O image icon. These images are in the files x.gif and o.gif.
I can see from the code that you're using PhotoImage before creating a main window gives you an Runtime error and it is clearly said in the error that "Too early to create image" means the image cannot be create if there is no active Tk window.
The reason why some people prefer the use other module because it give you more flexibility to resize, reshape, invert and more. ( By the way it could Pillow module from PIL import Image, ImageTk How to use PIL in Tkinter ).
Now back to your code.
You can randomise "O" and "X" images without even use of if-else.
I created main window before creating the Image.
Make sure the images you using are in the same directory.
import random
from tkinter import *
sign = random.choice( ["X.gif", "O.gif"] )
print(sign,"photo has been selected")
root = Tk()
Photo = PhotoImage(file=sign)
display_photo = Label(root, image=Photo)
display_photo.pack()
mainloop()
I have a folder which has some images. I want to display all the images using tkinter in a single window. Also whenever I click any image displayed in the window, I need to display the path of the image. I tried using for loop but it prints all the image file path. Here is the code I tried,
from Tkinter import *
import os
from PIL import ImageTk, Image
def getFileName(image):
print str(image)
gtk = Tk()
def showImages(folder):
for images in os.listdir(os.getcwd()):
if images.endswith("png"):
im = Image.open(images)
tkimage = ImageTk.PhotoImage(im)
imageButton = Button(gtk, image=tkimage, command=getFileName(images)
imageButton.image=tkimage
imageButton.pack()
gtk.mainloop()
Can anyone say what I'm doing wrong?
for images in os.listdir(os.getcwd()):
if images.endswith("png"):
im = Image.open(images)
tkimage = ImageTk.PhotoImage(im)
handler = lambda img = images: getFileName(img) #here modify
imageButton = Button(gtk, image=tkimage, command=handler)#here
imageButton.image=tkimage
imageButton.pack()
Because button-press callbacks are run with no arguments, if we
need to pass extra datato the handler, it must be wrapped in an object
that remembers that extra data and passes it along, by deferring the
call to the actual handler. Here, a button press runs the function
generated by the lambda, an indirect call layer that retains
information from the enclosing scope. The net effect is that the real
handler.
-- << Programming Python>> page 435
I have tried for several days to get an image displaying using the following code.
import Tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
path = "Aaron.jpg"
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()
The code is originally from this link.
How do I insert a JPEG image into a python Tkinter window?
When I run the code with my own path I get the following error messages
Python quit unexpectedly warning
and then:
The kernel appears to have died. It will restart automatically.
System info
Mac OS X Version 10.7.5
Anaconda
ipython-notebook version 3.2.1
Python 2.7.10-0
PIL 1.1.7
pillow 2.9.0
This is my first question on stackoverflow so please excuse any formatting errors. I will try to correct if there is an issue. I've also tried many version of code that is similar with the same result. This only happens with this specific code.
I want to set an image in my GUI application built on Python Tk package.
I tried this code:
root.iconbitmap('window.xbm')
but it gives me this:
root.iconbitmap('window.xbm')
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1567, in wm_iconbitmap
return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: bitmap "window.xbm" not defined
Can anyone help?
You want to use wm iconphoto. Being more used to Tcl/Tk than Python Tkinter I don't know how that is exposed to you (maybe root.iconphoto) but it takes a tkimage. In Tcl/Tk:
image create photo applicationIcon -file application_icon.png
wm iconphoto . -default applicationIcon
In Tk 8.6 you can provide PNG files. Before that you have to use the TkImg extension for PNG support or use a GIF. The Python PIL package can convert images into TkImage objects for you though so that should help.
EDIT
I tried this out in Python as well and the following worked for me:
import Tkinter
from Tkinter import Tk
root = Tk()
img = Tkinter.Image("photo", file="appicon.gif")
root.tk.call('wm','iconphoto',root._w,img)
Doing this interactively on Ubuntu resulted in the application icon (the image at the top left of the frame and shown in the taskbar) being changed to use my provided gif image.
This worked for me
from tkinter import *
raiz=Tk()
raiz.title("Estes es el titulo")
img = Image("photo", file="pycharm.png")
raiz.tk.call('wm','iconphoto',raiz._w, img)
raiz.mainloop()
Try this:
root.iconbitmap('#window.xbm')
And quote:
Set (get) the icon bitmap to use when this window is iconified. This method are ignored by some window managers (including Windows).
Note that this method can only be used to display monochrome icons. To display a color icon, put it in a Label widget and display it using the iconwindow method instead.
I want to get the photo(thumbnail) of a window which I already have it's handle (hwnd) using python in windows os.
From the link i posted in your question comments, I was able to get a sample working that thumbnails my python interpreter window.
from PIL import ImageGrab, Image
import win32gui
hwnd = 2622054 # My python intepreter window
thumbnailsize = 128, 128
# Set the current window to your window
win32gui.SetForegroundWindow(hwnd)
# Get the size of the window rect.
bbox = win32gui.GetWindowRect(hwnd)
# Grab the image using PIL and thumbnail.
img = ImageGrab.grab(bbox)
img.thumbnail(thumbnailsize, Image.ANTIALIAS)
# Save.
img.save('c:/test/test.png')