Button displaying white canvas instead of image [duplicate] - python

This question already has answers here:
Tkinter Label does not show Image
(3 answers)
Closed 7 years ago.
I'm trying to create an image, but it's not working and I'm not sure what I'm doing wrong. All I get when I click the button that should display the image is the white canvas, without the image. How do I get it to display?
def show_original(self):
from os.path import exists
from PIL import Image, ImageTk
if not os.path.exists(self.wdg_orig_file_name_.get()):
tkMessageBox.showinfo('Load','File does not exist:' + self.wdg_orig_file_name_.get())
return
self.orig_image_=Image.open(str_orig_file_name)
canvas = self.gui_.ca(500,500,bg='white')
im_TK = ImageTk.PhotoImage(self.orig_image_)
canvas.create_image(250,250,image=im_TK)
canvas.pack()
pass
self.wdg_orig_file_name_.get() in the main loop is:
self.wdg_orig_file_name_ = self.gui_.en(text='boat.png')
The global str_orig_file_name is assigned in pick_file():
def pick_file(self):
'''Opens a file dialog and sets its result to the filename entry'''
global str_orig_file_name
str_orig_file_name = tkFileDialog.askopenfilename()
if str_orig_file_name:
self.wdg_orig_file_name_.delete(0, END)
self.wdg_orig_file_name_.insert(0, str_orig_file_name)
#We got a new image to process. Forget the previous results.
self.orig_image_ = None
self.preview_image_ = None

Have you tried easygui?
#!/usr/bin/python
from easygui import *
image = "img.jpg"
msg = "Do you like this picture?"
choices = ["Yes","No","No opinion"]
reply=buttonbox(msg,image=image,choices=choices)
Very easy.
http://www.ferg.org/easygui/tutorial.html

I'm sorry. I though the OP was looking for a way to display an image and now I see the image is supposed to be on the button. Well I tried this and it works just fine with .gif and .png. However .jpg gives an error: "_tkinter.TclError: couldn't recognize data in image file "img.jpg"".
#!/usr/bin/python
from Tkinter import *
root=Tk()
b=Button(root,justify = LEFT)
photo=PhotoImage(file="img.png")
b.config(image=photo,width="100",height="100")
b.pack(side=LEFT)
root.mainloop()

Related

How to display adjusted PIL images in Tkinter? [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Tkinter PIL image not displaying inside of a function
(1 answer)
Closed 1 year ago.
I am attempting to make a simple Tkinter app that displays an image on screen, and that reduces the brightness of the image when you click:
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk, ImageEnhance
def update_image(img):
enhancer = ImageEnhance.Brightness(img)
temp_img = enhancer.enhance(0.5)
temp_tkimg = ImageTk.PhotoImage(temp_img)
panel.configure(image=temp_tkimg)
root = Tk()
img = Image.open('img.png')
tkimg = ImageTk.PhotoImage(img)
panel = ttk.Label(root, image=tkimg)
panel.pack(side="bottom", fill="both", expand="yes")
panel.bind('<1>', lambda e: update_image(img))
root.mainloop()
This correctly displays the initial image, but after clicking, instead of rendering the new image it just disappears. I've tried saving the temp_tkimg as a new png and reopening it the same way I do with the initial image but this doesn't work either:
def update_image(img):
enhancer = ImageEnhance.Brightness(img)
temp_img = enhancer.enhance(0.5)
temp_img.save('temp.png')
temp_tkimg = PhotoImage(file='temp.png')
panel.configure(image=temp_tkimg)
I feel like this is a pretty simple concept so not sure what I'm missing.
Cheers.

Tkinter:Cant place image which imported from Pixmap inside text widget using button

So i am using python 3 and got confused why the image doesnt show up in text widget after excuted the following code:
from tkinter import *
import fitz
root=Tk()
filenew=fitz.open(r'C:\Users\azoka\Desktop\Python\b.pdf')
text_1=Text(root,width=100,height=100,bg='gray').pack(side=LEFT,expand=FALSE)
def Show():
pix =filenew.getPagePixmap(0) # 0 is page number
pix1=fitz.Pixmap(pix,0)
img =pix1.getImageData("ppm")
timg=PhotoImage(data=img)
frame=[]
frame.append(timg)
text_1.image_create(END,image=timg)
Shower=Button(win1,text='show',bg='navy',fg='light cyan',width=5,height=1,command=Show)
Shower.place(x=1000,y=360)
root.mainloop()
The image just dont show up after clicked the button but it doesnt show any code error,I am new to python
and cant figure out. I want my img be shown without altering the Show()function.
-Appreciate for helpful answers!-
I tried to use the from previous code but not works
I made some fix with last version today, see fix bellow with simplifications
from tkinter import *
from PIL import Image, ImageTk
import fitz
root = Tk()
file = "yourfile.pdf"
doc = fitz.open(file)
page = doc.load_page(0) # loads page number 'pno' of the document (0-based)
pix = page.get_pixmap()
mode = "RGBA" if pix.alpha else "RGB"
img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
frame_image = ImageTk.PhotoImage(img)
label = Label(root, bg='gray')
label.pack(side=LEFT)
label.config(image=frame_image)
label.image = frame_image
root.mainloop()
requirements to use "PyMuPDF-1.21.1"
pip install --upgrade pymupdf
see more: https://pymupdf.readthedocs.io/

How to import and display list of images in GUI using Tkinter?

from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
# Function to display image
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
# gta_images = []
os.chdir("gta")
for file in glob.glob("*.jpg"):
# gta_images.append(str(file))
displayImg(file)
print(file)
# print(gta_images)
root.mainloop()
I am trying to load images from a folder called "gta" and then display those game logos on my app. Program has no error but I think its a logical error. I am new to Python I don't know maybe there is some scoping logic problem in my displayImg funcion.
Note: When a PhotoImage object is garbage-collected by Python (e.g.
when you return from a function which stored an image in a local
variable), the image is cleared even if it’s being displayed by a
Tkinter widget.
For more.
from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
photos = []
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
photos.append(photo)#keep references!
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
for file in glob.glob("*.jpg"):
displayImg(file)
print(file)
root.mainloop()
Not sure if it will work but try using the path of the gta folder you are getting the images from, instead of its name simply - replace the name with the path.

Tkinter: Window not showing image

I am new to GUI programming and recently started working with tKinter.
My problem is that the program won't show my image, I'm suspecing that it is my code that is wrong, however, I would like somone to exactly explain to me how i can make it work...
Here's my code:
from tkinter import * # Import the tkinter module (For the Graphical User Interface)
from PIL import ImageTk, Image
width = 1920
height = 1080
RootGeo = str(width) + "x" + str(height) # Make a def for RootGeo so the Root geometry isn't hardcoded
def MakeWindow():
# -----Root_Attributes-----
Root = Tk()
Root.geometry(RootGeo)
Root.state("zoomed")
# -----Root_Attributes, Root_Containers----- ### NOT WORKING ###
__DISPlAY__ = Image.open("Display.png")
__DISPLAY_RENDER__ = ImageTk.PhotoImage(__DISPlAY__)
Display_icon = Label(Root, image=__DISPLAY_RENDER__)
Display_icon.image = __DISPLAY_RENDER__
Display_icon.place(x=0, y=0)
# -----Root_Containers----- ### NOT WORKING ###
Root.mainloop()
MakeWindow()
Any and all help would be very appreciated.
try to change the image and check out if its still not showing up.
if its still not showing up, try to change this line:
__DISPlAY__ = Image.open("Display.png")
to
__DISPlAY__ = Image.open("Display.png").resize((600,800))
see if it would show up now then change the width and height as you like.
Pychamarm does not want to show the images, so to solve this problem i had to run the script from cmd every time...

Viewing external images in a list (Tkinter in python)

im trying to learn Python and doing some test apps.
Right now im creating a type of image viewer for viewing external images. But have some problems.
I've successfully worked out on how to view the image. But i need to view it as a function, so the image can be updated.
This is what i use for just viewing the image:
from io import BytesIO
import urllib
import urllib.request
import tkinter as tk
from PIL import Image, ImageTk
imagelinks = []
***** Here is a crawler that provides image urls from a webpage into the above list ***
root = tk.Tk()
listvalue = 1
url = (imagelinks[listvalue])
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
root.mainloop()
Everything works well, the image 1 from the list shows up properly.
The problem im having is that i want to add a prev and next button which increment the value of listvalue-=1 and +=1 but simply doing that wont work since it wont update the image in the tkinter window.
Also tried with the Tkinter's update() in my buttons function, but didn't help much either.
Anyone got some input on how to get it to work?
Update:
Tried to put it in a function like this. It is resizing the windows to the proper size, but wont show the image.
from io import BytesIO
import urllib
import urllib.request
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
link='http://img.khelnama.com/sites/default/files/previewimage/features/2013/Aug/IMG- Reliance_logo(1).jpg'
def showimg(currentimg):
url = currentimg
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
showimg(link)
root.mainloop()
You will need to put your code that retrieves and displays the image in a definition, and pass the list item that it is meant to use as a parameter. That way on a button press, you can increment or decrement the index, and call your own update function you made.
Edit:
Try this then
label = tk.Label()
label.pack()
def showimg(currentimg, label):
url = currentimg
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label.config(image = image)
showimg(link, label)

Categories

Resources