Currently, the code chooses images from a folder and displays it on the tkinter window. I can click 'Next image' to see the next image from the folder. I would like to make the images clickable, so that it take would take me to a specified link. I can make it clickable but not sure how to bind the different links to each image. It will get confusing if I were to randomize the images(planning to do this later)
import tkinter as tk
from tkinter.filedialog import askdirectory
import os
img_list = []
def save_to_list(event):
click_loc = [event.x, event.y]
print ("you clicked on", click_loc)
img_list.append(click_loc)
def next_img():
img_label.img = tk.PhotoImage(file=next(imgs))
img_label.config(image=img_label.img)
root = tk.Tk()
root.geometry('500x500')
# Choose multiple images
img_dir = askdirectory(parent=root, initialdir="./yoga_Images/", 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_to_list)
btn = tk.Button(root, text='Next image', command=next_img)
btn.pack()
next_img()
root.mainloop()
You can simply specify a image object when creating a button.
from PIL import Image, ImageTk
import tkinter as tk
def example():
print("Clickable Image!")
root = tk.Tk()
image = Image.open("image.png")
btnPhoto= ImageTk.PhotoImage(image)
imgBtn = tk.Button(root, image=btnPhoto, command=example)
imgBtn.pack()
root.mainloop()
Here is some code if you want to make multiple clickable images, don't forget to specify your image directory (Apologies for using list comprehensions, I know they are somewhat confusing).
from PIL import Image, ImageTk
import tkinter as tk
import os
def example():
print("Clickable Image!")
root = tk.Tk()
imgDir = "imgs"
images = [ImageTk.PhotoImage(Image.open(os.path.join(imgDir, imgName))) for imgName in os.listdir(imgDir)]
for img in images:
imgBtn = tk.Button(root, image=img, command=example)
imgBtn.pack()
root.mainloop()
Related
img= (Image.open("image/frame.png")).resize((240, 240), Image.ANTIALIAS)
new_image = ImageTk.PhotoImage(img)
panel = tk.Label(right_workspace, image=new_image)
panel.pack(side = "top", fill = "none", expand = "none", pady=29)
Thats my label with its image background. Now how can I change this background by a function so everytime my program generates a new qrcode from an input it replaces previous background?
I gather what you're doing, but please leave a minimum reproducible code in future.
Here's an example of how you'd create a functioning tkinter GUI that displays a random image from a list of QR .pngs in a set folder when the button is pressed. You should be able to adapt this to the other part of your program that generates the QR code for you.
import tkinter as tk
from PIL import Image, ImageTk
import os
import random
class QrGenerator:
def __init__(self, main):
self.main = main
self.panel = tk.Label(main)
self.panel.grid(row=0, column=0)
self.button = tk.Button(main, text='Random QR', command=self.random_qr)
self.button.grid(row=1, column=0)
def random_qr(self):
fp = r'C:\Filepath\QR Codes Folder'
os.chdir(fp)
qr_code = random.choice(os.listdir(fp))
print(qr_code)
img = Image.open(qr_code).resize((240, 240), Image.ANTIALIAS)
new_image = ImageTk.PhotoImage(img)
self.panel.configure(image=new_image)
self.panel.image = new_image
if __name__ == '__main__':
root = tk.Tk()
gui = QrGenerator(root)
root.mainloop()
I am doing a people counter in raspberry pi. I want to display an one image if someone comes in, and another one if someone comes out. Right now i am using the code below (that i took from another question here xd) to change the image that tkinter is displaying. The problem with this is thay it only shows the picture cat.jpg for a second, and then it shows a black screen and nothing happends.
import sys
if sys.version_info[0] == 2: # the tkinter library changed it's name from Python 2 to 3.
import Tkinter
tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
import tkinter
from PIL import Image, ImageTk
import time
def updateRoot(root,imagen):
pilImage = Image.open(imagen)
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
canvas = tkinter.Canvas(root,width=w,height=h)
canvas.pack()
canvas.configure(background='black')
imgWidth, imgHeight = pilImage.size
if imgWidth > w or imgHeight > h:
ratio = min(w/imgWidth, h/imgHeight)
imgWidth = int(imgWidth*ratio)
imgHeight = int(imgHeight*ratio)
pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pilImage)
imagesprite = canvas.create_image(w/2,h/2,image=image)
root.update()
root = tkinter.Tk()
updateRoot(root,"Cat.jpg")
time.timesleep(5)
updateRoot(root,"Dog.jpg")
Before this I used this code
import tkinter
from PIL import Image, ImageTk
from tkinter import ttk
def updateRoot(root,imagen):
image1 = Image.open(imagen)
image2 = ImageTk. PhotoImage(image1)
image_label = ttk. Label(root , image =image2)
image_label.place(x = 0 , y = 0)
root.update()
That works fine, but it's not full screen.
First you should do the followings outside updateRoot():
make root window fullscreen (you can simply use root.attributes('-fullscreen', 1))
bind the <Escape> key
create the canvas and create_image() (you can use Label to do the same thing)
Then just update the image inside updateRoot().
Also you should use after() instead of time.sleep().
Below is an example:
try:
import Tkinter as tkinter
except:
import tkinter
from PIL import Image, ImageTk
def updateRoot(imagen):
# resize the image to fill the whole screen
pilImage = Image.open(imagen)
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
image = ImageTk.PhotoImage(pilImage.resize((w,h)))
# update the image
canvas.itemconfig(imgbox, image=image)
# need to keep a reference of the image, otherwise it will be garbage collected
canvas.image = image
root = tkinter.Tk()
root.attributes('-fullscreen', 1)
root.bind('<Escape>', lambda _: root.destroy())
canvas = tkinter.Canvas(root, highlightthickness=0)
canvas.pack(fill=tkinter.BOTH, expand=1)
imgbox = canvas.create_image(0, 0, image=None, anchor='nw')
# show the first image
updateRoot('Cat.jpg')
# change the image 5 seconds later
root.after(5000, updateRoot, 'Dog.jpg')
root.mainloop()
Fixed your Black issue using labels, try this. i think you still need to resize image to fit screen
import sys
if sys.version_info[0] == 2: # the tkinter library changed it's name from Python 2 to 3.
import Tkinter
tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
import tkinter
from PIL import Image, ImageTk
import time
from tkinter import *
import PIL.Image
def updateRoot(root,imagen):
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
img = PIL.Image.open(imagen)
root.tkimage = ImageTk.PhotoImage(img)
Label(root,image = root.tkimage).place(x=0, y=0, relwidth=1, relheight=1)
root.update()
root = tkinter.Tk()
updateRoot(root,"Cat.jpg")
time.sleep(3)
updateRoot(root,"Dog.jpg")
root.mainloop()
So im trying to make an app that will display images, and the image I have is 1000*1000 but this is way too big, I need a way to resize the image. I've tried using PIL and ImageTK but that didn't work, here's my code so far:
from tkinter import *
app = Tk()
app.title('embeded image')
fname = Canvas(bg = 'black', height=100, width=100)
fname.pack(side=TOP)
image = PhotoImage('Sun.png')
image = image.resize((25, 25), Image.ANTIALIAS)
icon = fname.create_image(image=image)
fname.pack()
app.mainloop()
I've no idea why this doesn't work, im relatively new to Tkinter so sorry if it's obvious.
You mix two differnt class PhotoImage in tkinter which doesn't have resize and PIL.Image which have resize
import tkinter as tk
from PIL import Image, ImageTk
app = tk.Tk()
fname = tk.Canvas(height=200, width=200)
fname.pack()
pil_image = Image.open('Sun.png')
pil_image = pil_image.resize((25, 25), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pil_image)
icon = fname.create_image((0,0), image=image, anchor='nw')
app.mainloop()
So I made a script in python with Tkinter and the thing is that the first Tkinter window pops up without problems but when the code goes to the second window it says :
_tkinter.TclError: image "pyimage1" doesn't exist
and I didn't find anything that helped me, could someone help me please ?
Here is the code :
from Tkinter import *
from PIL import ImageTk, Image
def choose():
global name, chosen
name = name1.get()
chosen = chosen1.get()
print name
print chosen
root0.quit()
root0 = Tk()
name1 = Entry(root0)
name1.pack()
chosen1 = Entry(root0)
chosen1.pack()
Button(root0, text="ENTER", command=choose).pack()
root0.mainloop()
root = Tk()
img = ImageTk.PhotoImage(Image.open('person1.png'))
panel1 = Label(root, image = img)
panel1.pack(side="left")
img2 = ImageTk.PhotoImage(Image.open('person2.png'))
panel2 = Label(root, image = img2)
panel2.pack(side="right")
root.mainloop()
by the way, the python version is 2.7
This is a side effect of using 2 roots (Tk() instances). The images default to associate with the first root window. The quick fix is to provide the image with the correct root:
img2 = ImageTk.PhotoImage(Image.open('person2.png'), master=root)
The proper fix is to never use more than one Tk(). Put all your code into Frame instances, and then destroy one and load the other when the time is right:
import Tkinter as tk
def choose():
global name, chosen
name = name1.get()
chosen = chosen1.get()
print name
print chosen
frame0.destroy() # kill this frame
frame1.pack() # open new frame
root = tk.Tk()
frame0 = tk.Frame(root)
name1 = tk.Entry(frame0)
name1.pack()
chosen1 = tk.Entry(frame0)
chosen1.pack()
tk.Button(frame0, text="ENTER", command=choose).pack()
frame1 = tk.Frame(root)
img = ImageTk.PhotoImage(Image.open('person1.png'))
panel1 = tk.Label(frame1, image = img)
panel1.pack(side="left")
img2 = ImageTk.PhotoImage(Image.open('person2.png'))
panel2 = tk.Label(frame1, image = img2)
panel2.pack(side="right")
#start the program
frame0.pack() # load frame0
root.mainloop()
Note I also moved you away from the evil wildcard imports (from module import *).
I have a folder with images, I'm using tkinter and PIL to show the images in a directory. But, whenever I run the following code it doesn't shows any image. Here is the code I tried,
from Tkinter import *
import os
from PIL import Image, ImageTk
def getFileName(image):
print str(image)
def CropManual():
global outputFile
#getCrop(outputFile)
print "Crop Manual"
def showImages(folder):
print "loading....", folder
gtk = Tk()
gtk.wm_title("Images")
row, col = 0,0
for images in os.listdir(folder):
print images
im = Image.open(images)
#im = im.resize(250, 250, Image.ANTIALIAS)
tkimage = ImageTk.PhotoImage(im)
handler = lambda img = images : getFileName(img)
imageButton = Button(gtk, image=tkimage, command=handler)
imageButton.image=tkimage
imageButton.grid(row=row+1, column=col+1, padx=3, pady=3)
row +=1; col+=1;
userCrop = Button(gtk, text="Crop Manually?", command=CropManual)
userCrop.grid(row=row+1, column=col+1, padx=3, pady=3)
gtk.mainloop()
showImages("/home/yogaraj/Music/Image1487915648.54/")
The image folder is here.
Here is the error I get
It shows no such file or directory though the file is present. Can anyone help me out with this issue?
You must pass the absolute path of the image
Change
im = Image.open(images)
to
im = Image.open(folder + images)
or better
im = Image.open(os.path.join(folder, images))