That's my code and I get the error message:
... return getattr(self.tk, attr)
AttributeError: temp_pic"...
I need to program two buttons: [zoom in] and [zoom out].
If you have any better ideas for doing that, please, just say it.
I'm going to use this image to develop maps through graphs (structure)
from Tkinter import *
from PIL import Image, ImageTk, ImageDraw, ImageOps, ImageEnhance
bairro = "botafogo.jpg"
class Painel(Tk):
def __init__(self):
Tk.__init__(self) #create ui
self.zoom = Frame(self)
self.zoom.pack()
self.zin = Button(self.zoom, command = self.zoom_in, text = "Zoom In")
self.zin.pack()
self.zout = Button(self.zoom, command = self.zoom_out, text = "Zoom Out")
self.zout.pack()
self.c = Canvas(self, bd=0, highlightthickness=0, width=100, height=100)
self.c.pack(fill='both', expand=1)
self.main_pic = Image.open(bairro) #load image
self.main_pic.thumbnail((800, 600))
self.tkphoto = ImageTk.PhotoImage(self.main_pic)
self.canvasItem = self.c.create_image(0, 0, anchor='nw', image = self.tkphoto)
self.c.config(width = self.main_pic.size[0], height = self.main_pic.size[1])
self.temp = self.main_pic.copy() # 'working' image
def update_painel(self):
self.tkphoto = ImageTk.PhotoImage(self.temp_pic)
self.c.itemconfigure(self.canvasItem, image = self.tkphoto)
def zoom_in(self):
self.temp_pic = self.temp_pic.transform( ( self.temp_pic.size[0]/2,
self.temp_pic.size[0]/2
),
Image.EXTEND,
( 0, 0, self.temp_pic[0], self.temp_pic[1]
)
)
self.update_painel()
def zoom_out(self):
self.temp_pic = self.main_pic
self.update_painel()
app = Painel()
app.mainloop()
a deep-copy instruction shall read
self.temp_pic = self.main_pic.copy() # 'working' image
instead of
self.temp = self.main_pic.copy() # 'working' image**
Related
The code provided here is:
import tkinter as tk
from PIL import Image, ImageTk
from pathlib import Path
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('600x600')
self.img_path = Path(r'D:\Python\Lena.jpg')
self.img = Image.open(self.img_path)
self.img_rgb = self.img.convert('RGB')
dim_x, dim_y = self.img_rgb.size
self.img_tk = ImageTk.PhotoImage(self.img_rgb.resize((dim_x, dim_y)))
self.canvas = tk.Canvas(self)
self.canvas.create_image(dim_x // 2, dim_y // 2, image=self.img_tk)
self.canvas.pack(expand=True, fill=tk.BOTH)
self.rgb_var = tk.StringVar(self, '0 0 0')
self.rgb_label = tk.Label(self, textvariable=self.rgb_var)
self.rgb_label.pack()
self.bind('<Motion>', lambda e: self.get_rgb(e))
def get_rgb(self, event):
x, y = event.x, event.y
try:
rgb = self.img_rgb.getpixel((x, y))
self.rgb_var.set(rgb)
except IndexError:
pass # ignore errors if the cursor is outside the image
if __name__ == '__main__':
app = App()
app.mainloop()
It displays an image with the RGB value of the pixel under the mouse pointer under the image (when the mouse pointer is over the image). The image used is this.
However, only the upper left quadrant of the image is displayed on the canvas. You can see that in the screenshot below.
How can I display the whole image and still have the RGB values of the pixel under the mouse pointer displayed (when the mouse pointer is over the image)?
I can see two possible solutions:
Expand image to fit window
Wrap window around image
To expand image to fit window
dim_x, dim_y = 600, 600
self.img_tk = ImageTk.PhotoImage(self.img_rgb.resize((dim_x, dim_y)))
OR
To wrap window around image
dim_x, dim_y = self.img_rgb.size
self.img_tk = ImageTk.PhotoImage(self.img_rgb)
Both approaches will display the entire image.
Here is the complete code with both options available via select flag.
import tkinter as tk
from PIL import Image, ImageTk
from pathlib import Path
class App(tk.Tk):
def __init__(self, select = True):
super().__init__()
self.img_path = Path('D:\Lenna.jpg')
self.img = Image.open(self.img_path)
self.img_rgb = self.img.convert('RGB')
if select:
# resize image to fit window
dim_x, dim_y = 600, 600
self.img_tk = ImageTk.PhotoImage(self.img_rgb.resize((dim_x, dim_y)))
else:
# resize window to fit image
dim_x, dim_y = self.img_rgb.size
self.img_tk = ImageTk.PhotoImage(self.img_rgb)
self.geometry(f'{dim_x}x{dim_y+21}')
self.canvas = tk.Canvas(self, borderwidth = 0, highlightthickness = 0)
self.canvas.create_image(0, 0, image = self.img_tk, anchor= tk.NW)
self.canvas.pack(expand=True, fill=tk.BOTH)
self.rgb_var = tk.StringVar(self, '0 0 0')
self.rgb_label = tk.Label(self, textvariable=self.rgb_var)
self.rgb_label.pack()
self.bind('<Motion>', lambda e: self.get_rgb(e))
def get_rgb(self, event):
x, y = event.x, event.y
try:
rgb = self.img_rgb.getpixel((x, y))
self.rgb_var.set(rgb)
except IndexError:
pass # ignore errors if the cursor is outside the image
if __name__ == '__main__':
app = App(False)
app.mainloop()
Everything works as expected when borderwidth and highlightthickness are removed.
I'm currently working on Tkinter and image stuff in a program. I want to display 9 images on the screen at the same time, but only one image(the last one)will appear on screen at one time. I've isolated the problem in this code so this is the fraction of my code that is causing this problem. The function "download" receives the images from the internet, and then "ext" takes the downloaded images and is supposed to put them on the screen, but not all of them go on.
import tkinter as tk
from tkinter.ttk import *
from threading import *
import random
from io import BytesIO
import urllib
import urllib.request
from PIL import Image, ImageTk
class CardClass:
def __init__(self):
self.master = tk.Tk()
self.master.attributes('-zoomed', True)
self.frame = Frame(self.master)
self.frame.pack()
self.state = False
self.master.attributes("-fullscreen", True)
self.but = Button(self.master, text="Print Images", command=self.Hand, pad = 150)
self.but.pack(pady = 12)
self.cardsList = ["https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg"]
def Hand(self):
self.but.destroy()
self.newCard = random.sample(self.cardsList, k=9)
self.slot1 = self.cardsList[0]
self.slot2 = self.cardsList[1]
self.slot3 = self.cardsList[2]
self.slot4 = self.cardsList[3]
self.slot5 = self.cardsList[4]
self.slot6 = self.cardsList[5]
self.slot7 = self.cardsList[6]
self.slot8 = self.cardsList[7]
self.slot9 = self.cardsList[8]
self.ext()
def download(self, url, ex, ey):
print("here1")
with urllib.request.urlopen(url) as u:
raw_data = u.read()
img = Image.open(BytesIO(raw_data))
self.iimage = ImageTk.PhotoImage(img.resize((50,50), Image.ANTIALIAS))
lala = tk.Label(image=self.iimage)
lala.place(x=ex, y=ey)
return self.iimage
def ext(self):
self.download(self.newCard[0], 50, 150)
self.download(self.newCard[1], 100, 150)
self.download(self.newCard[2], 150, 150)
self.download(self.newCard[3], 200, 150)
self.download(self.newCard[4], 150, 150)
self.download(self.newCard[5], 300, 150)
self.download(self.newCard[6], 350, 150)
self.download(self.newCard[7], 400, 150)
self.download(self.newCard[8], 450, 150)
if __name__ == '__main__':
w = CardClass()
w.master.mainloop()
Does anybody know why this is happening? Thank you!
I don't think I understand why this should be, but the problem is, in fact, that the ImageTk.PhotoImage instances evaporate when the function ends. That shouldn't be the case. The Label widget should be holding a reference that keeps it alive, but if you store those PhotoImage objects in a list, as below, the code works:
def Hand(self):
self.but.destroy()
self.newCard = random.sample(self.cardsList, k=9)
self.keep = []
self.ext()
def download(self, url, ex, ey):
with urllib.request.urlopen(url) as u:
raw_data = u.read()
img = Image.open(BytesIO(raw_data)).resize((50,50),Image.ANTIALIAS)
iimage = ImageTk.PhotoImage(img)
Label(self.master, image=iimage).place(x=ex,y=ey)
self.keep.append(iimage)
So I am trying to make a desktop-like interface in python with Tkinter, and I am trying to set the wallpaper but I have no idea how to resize it. Here is the code:
from tkinter import *
import tkinter.messagebox as box
import webbrowser
from PIL import Image, ImageTk
window=Tk()
window.title('Label Example')
window.configure(background = 'gray44')
#---=Main_Frame=---#
main_frame = Frame(window)
main_frame.pack(padx = 600, pady=350)
#---=Wallpaper=---#
img_wallpaper = ImageTk.PhotoImage(Image.open('minecraft main picture.gif').resize(10, 10)) # the one-liner I used in my app
label_w = Label(window, image=img_wallpaper)
label_w.image = img_wallpaper # this feels redundant but the image didn't show up without it in my app
label_w.pack()
##wallpaper_image = PhotoImage(file = 'minecraft main picture.gif')
##wallpaper = Label(window, image= wallpaper_image, width=400, height = 400)
##wallpaper_image_big = PhotoImage.subsample(wallpaper_image, x=1, y=1)
##can_wallpaper = \
##Canvas(window, width = 1200, height = 700)
##can_wallpaper.create_image((100, 100), image = wallpaper_image)
##can_wallpaper.place(x=0, y =0)
window.mainloop() #Main loop
I have tried used someone else's code to resize it with PIL pillow but it does not work.
Here is the error:
Traceback (most recent call last):
File "/Users/edwardandreilucaciu/Desktop/Desktop Interface Project/Desktop Interface.py", line 16, in <module>
img_wallpaper = ImageTk.PhotoImage(Image.open('minecraft main picture.gif').resize(10, 10)) # the one-liner I used in my app
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/Image.py", line 1865, in resize
message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
ValueError: Unknown resampling filter (10). Use Image.NEAREST (0), Image.LANCZOS (1), Image.BILINEAR (2), Image.BICUBIC (3), Image.BOX (4) or Image.HAMMING (5)
Question: how to resize images in Tkinter
import kinter as tk
from PIL import Image, ImageTk
class ImageLabel(tk.Label):
def __init__(self, parent, **kwargs):
path = kwargs.pop('path', None)
if path is not None:
image = Image.open(path)
resize = kwargs.pop('resize', None)
if resize is not None:
image = image.resize(resize, Image.LANCZOS)
# Keep a reference to prevent garbage collection
self.photo = ImageTk.PhotoImage(image)
kwargs['image'] = self.photo
super().__init__(parent, **kwargs)
Usage:
class App(tk.Tk):
def __init__(self):
super().__init__()
lab=ImageLabel(self,
path="minecraft main picture.gif",
resize=(400, 400))
lab.grid()
if __name__ == '__main__':
App().mainloop()
It's actually quite easy
img_wallpaper = ImageTk.PhotoImage(Image.open('minecraft main picture.gif').resize(10, 10))
you see .resize is not availble for ImageTk image object also .resize takes a tuple of width and height
Try this
img_wallpaper = Image.open('minecraft main picture.gif').resize((10,10))
img_wallpaper = ImageTk.PhotoImage(img_wallpaper)
i'm taking the image from the user, and displaying it using label. Now i have to use that image for further processing.
my code is:
from Tkinter import Tk, Frame, BOTH
from Tkinter import *
import cv2
from collections import *
from experiment import *
from scipy.spatial import distance
import Tkinter,tkFileDialog
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("PISE")
self.pack(fill=BOTH, expand=1)
def query():
path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()
myvar.place(x = 850, y = 5)
custName.set(path)
cont_list1 = list()
ene_list1 = list()
homo_list1 = list()
cor_list1 = list()
B_mean1 = list()
G_mean1 = list()
R_mean1 = list()
graylist1 = list()
resizelist1 = list()
eq_graylist1 = list()
dis_list1 = list()
imge = cv2.imread(tkimage)
arr = array(imge)
g_img = cv2.imread(tkimage,0)
gray_re_img = cv2.resize(g_img,(256,256))
graylist1.append(gray_re_img)
equ = cv2.equalizeHist(gray_re_img)
eq_graylist1.append(equ)
re_img = cv2.resize(imge,(256,256))
resizelist1.append(re_img)
blue, green, red = cv2.split(re_img)
total = re_img.size
B = sum(blue) / total
G = sum(green) / total
R = sum(red) / total
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)
im = skimage.io.imread(tkimage, as_grey=True)
im = skimage.img_as_ubyte(im)
im /= 32
g = skimage.feature.greycomatrix(im, [1], [0], levels=8, symmetric=False, normed=True)
cont = skimage.feature.greycoprops(g, 'contrast')[0][0]
cont_list1.append(cont)
ene = skimage.feature.greycoprops(g, 'energy')[0][0]
ene_list1.append(ene)
homo = skimage.feature.greycoprops(g, 'homogeneity')[0][0]
homo_list1.append(homo)
cor = skimage.feature.greycoprops(g, 'correlation')[0][0]
cor_list1.append(cor)
dis = skimage.feature.greycoprops(g, 'dissimilarity')[0][0]
dis_list1.append(dis)
feature_matrix_ip = zip( B_mean1 , G_mean1 , R_mean1, cont_list1 , ene_list1 , homo_list1 , cor_list1 , dis_list1)
root = Tk()
root.geometry("1105x605+300+300")
app = Example(root)
custName = StringVar(None)
yourName = Entry(app, textvariable=custName)
yourName.focus_set()
yourName.pack(padx = 20, pady = 20,anchor='n')
yourName.place(y = 25, x = 100, width = 500, height = 25)
button1 = Button(app, text='Select the Query Image',command = query)
button1.pack(padx = 2, pady = 2,anchor='ne')
button1.place( x = 550, y = 25)
root.mainloop()
but its giving me an error like:
imge = cv2.imread(tkimage)
TypeError: expected string or Unicode object, instance found
how to overcome this error??
thanks for your support!
You are giving cv2.imread a PhotoImage instance, but it expects a filename. Give it path instead.
imge = cv2.imread(path)
When I load a transparent image with:
def load_image(path):
img = Image.open(path)
return ImageTk.PhotoImage(img)
class Home_Screen(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.home = Tk()
self.home.resizable(width = False,height = False)
self.home.geometry("700x500+300+100")
self.start()
def run(self):
self.images()
Label(self.home, image = self.background).pack() # Put it in the display window
button_instructions = Label(self.home,image = self.b_instructions).place(x = 300,y = 200)
self.home.mainloop()
def images(self):
self.background = load_image("Images/night-sky.jpg")
self.b_instructions = load_image("button_instructions.png")
def start_game(self):
self.home.destroy()
Home = Home_Screen()
I get an image with a white border around it. Does anyone know why the original transparency was not retained? If so could you please offer a solution.
Use a Canvas instead of Label widgets. The transparency isn't getting lost, because what you see is the background of the widget.
def run(self):
img_sky = ImageTk.PhotoImage(file="Images/night-sky.jpg")
img_button = ImageTk.PhotoImage(file="button_instructions.png")
self.canvas = Canvas(self.home, width=700, height=500)
self.canvas.create_image(0, 0, image=img_sky)
self.canvas.create_image(300, 200, image=img_button)
self.canvas.pack()
self.home.mainloop()