How can my program show image when I click button? [duplicate] - python

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 10 months ago.
I was trying to show the image when I clicked the button however it failed( the program does not report an error but the image is still not displayed). I'm sure I put the right path to the picture. This is code
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
def def_btn1():
image1 = Image.open("csdl.png")
image1 = image1.resize((710, 400), Image.ANTIALIAS)
test = ImageTk.PhotoImage(image1)
lbl2 = tk.Label(image=test)
lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command=def_btn1)
btn1.pack()
window = tk.mainloop()
I want when I click the button the image will show in the program. Thank you!

You need to add lbl2.image = test for the image to not be destroyed by tkinter, you new code should be this -
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk() # You might want to move this line below your functions, with the other global variables
def def_btn1():
image1 = Image.open("csdl.png")
image1 = image1.resize((710, 400), Image.ANTIALIAS)
test = ImageTk.PhotoImage(image1)
lbl2 = tk.Label(image=test)
lbl2.image = test # You need to have this line for it to work, otherwise it is getting rid of the image. the varibale after the '=' must be the same as the one calling "ImageTk.PhotoImage"
lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command= lambda : def_btn1()) # adding 'lambda :' stops the function from running straight away, it will only run if the button is pressed
btn1.pack()
window = tk.mainloop()

Related

Photo not displaying in Tkinter [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 6 months ago.
I am trying to make a sprite sheet editor.
I have a button where you can select an image.
When I put the code in a function it doesn't work, but when it is outside a function it does work.
The BrowseComputer function is what I am having a problem with
from tkinter import *
from tkinter import filedialog
#Window specs
window = Tk()
window.title("TileSplit")
window.configure(background="white")
filepath = ""
#Searches computer and displays Image
def BrowseCompter():
filepath = filedialog.askopenfilename()
photo = PhotoImage(file = filepath)
print(filepath)
SelectedImage = Label(window, image=photo, bg="White").grid(row=0,column=0)
#Makes a variable with information about the instruction text on the screen, Sets the text background, Text color, font and location
InstructionsLabel = Label(window, text="Please select the image you would like to split:" ,bg="white" ,font= "none 12 bold")
EmptyLabel = Label(window, text="" ,bg="white" ,font= "none 12 bold")
#Makes a button
ImportImageButton = Button(window, text="Browse:", command=BrowseCompter)
#Location data
InstructionsLabel.grid(row=0, column=60, sticky=E)
ImportImageButton.grid(row=3,column=0)
EmptyLabel.grid(row=1, column=0)
#Tells python to make the window
window.mainloop()
I think you have a typo. The function shown is actually named 'BrowseCompter'.
also you might need to change your command in the button from 'BrowseCompter' to 'BrowseCompter()'

display image by clicking a button tkinter [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 9 months ago.
I am trying to display an image in a window with tkinter, by clicking a button.
I created this function :
def tabuim():
tabu = Frame(win, width=600, height=400)
tabu.pack()
tabu.place(anchor='center', relx=0.8, rely=0.35)
img2 = ImageTk.PhotoImage(Image.open("Tabu.jpg"), master=win)
label2 = Label(tabu, image = img2, borderwidth=3, relief="solid")
label2.pack()
with this button :
button2 = Button(win, text = 'Tabu Route Solution', command = tabuim)
button2.place(relx = 0.5, rely = 0.5)
But it partially works. It only show a border without my image...
Thanks for you help
The following example displays a background image in a frame:
Import tkinter
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
Create a photoimage object of the image in the path
image1 = Image.open("<path/image_name>")
test = ImageTk.PhotoImage(image1)
label1 = tkinter.Label(image=test)
label1.image = test
Position image
label1.place(x=<x_coordinate>, y=<y_coordinate>)
root.mainloop()
This an example you can do as instead of resizing before loading the page you could resize after the image is loaded.

Images not getting applied on the button in Tkinter

The following project is supposed to show a message when clicking a certain colored button. But, whenever I execute the program it shows blank(white) buttons in the correct alignment, etc. Due to some reason the images are not loaded.
In future, I plan to add different images hence testing with colored image created in Paint and not in-built commands to show the color.
I will add the result below after the code.
Edit: All images are 100x100 pixels created in Microsoft Paint.I have tried other modules like PIL but to no avail.
# importing the module
import tkinter
import tkinter.messagebox
from tkinter import *
# importing the module
# initialising tkinter
class window(Frame):
def __init__(self,master = None):
Frame.__init__(self,master)
self.master = master
# initialising tkinter
# creating the window
root = Tk()
app = window(root)
root.geometry("350x350")
# creating the window
# colours
WHITE = (255,255,255)
BLACK = (0,0,0)
BLUE = (0,0,255)
RED = (255,0,0)
# colours
# image
red_image = "red.png"
blue_image = "blue.png"
yellow_image = "yellow.png"
green_image = "green.png"
# image
# creating a button function
def create_button(x,y,color,color2,picture):
click = Button(root, image = PhotoImage(picture), width= 150, height=150, command = lambda : tkinter.messagebox.showinfo( "Hello Python", "This is " + color))
click.image = PhotoImage(picture)
click.grid( row = x, column = y)
# creating a button function
create_button(0,0,'red','pink',red_image)
create_button(0,2,'blue','lightblue',blue_image)
create_button(2,0,'green','lightgreen',green_image)
create_button(2,2,'yellow','lightyellow',yellow_image)
# starting the widget
root.mainloop()
# starting the widget
There are two issues in your code:
You passed filename to PhotoImage() without using file keyword: PhotoImage(picture) should be PhotoImage(file=picture)
You did not keep the reference of the image assigned to button, but another instance of image
Below is the updated create_button() function that fixes the issues:
def create_button(x, y, color, color2, picture):
image = PhotoImage(file=picture)
click = Button(root, image=image, width=150, height=150, command=lambda: tkinter.messagebox.showinfo("Hello Python", "This is "+color))
click.image = image
click.grid(row=x, column=y)
For adding image in Button you have not use appropriate keywords.
Here is a simple example for you to add image in button
from tkinter import *
from tkinter.ttk import *
# creating tkinter window
root = Tk()
# Adding widgets to the root window
Label(root, text = 'Image adding', font =( 'Verdana',15)).pack(side = TOP, pady = 10)
# Creating a photoimage object to use image
photo = PhotoImage(file = "C:\Gfg\circle.png")
# here, image option is used to
# set image on button
Button(root, text = 'Click Me !', image = photo).pack(side = TOP)
root.mainloop()
I think it may help you

My Tkinter photo is packed, but it shows as a blank

I can't seem to get the picture to show up on screen while having a toplevel frame on top of my main one (root). This one is just called "frame". I have circled the outline of the tkinter Frame on the included photo in this post. When I resize the picture, the green frame outline changes, but the picture itself won't show up.
I also tried to pack it on my main root window, with success, which suggests it's a toplevel window issue. I just don't know what it is. Any ideas?
Here is my code:
def show_topLevelWindow():
from tkinter import ttk
print("Entered to show results")
window_linkedin = Toplevel(root)
window_linkedin.geometry('1000x590')
frame = Frame(window_linkedin)
frame.pack()
error_frame = tkinter.Frame(frame, highlightbackground="green", highlightcolor="green", highlightthickness=1)
error_label = Label(frame, text="It appears there are no results for the selected country")
error_label.config(font=("Helvetica Neue", 20))
im_error = Image.open("./ressources/images_gui/aw_snap.png")
im_error = im_error.resize((500, 500), Image.ANTIALIAS)
im_error = ImageTk.PhotoImage(file = "./ressources/images_gui/aw_snap.png")
im_error_label = Label(frame, image=im_error)
try:
if ....:
....unimportant code ....
else:
error_label.pack(in_=error_frame)
im_error_label.pack(in_=error_frame)
error_frame.pack(anchor="center")
except Exception as e:
error_label.pack(in_=error_frame)
im_error_label.pack(in_=error_frame)
error_frame.pack(anchor="center")
Packed image shows as blank
The single most important issue you are having is your image is not being saved for reference. if you add global im_error to the very top of your function your image will be visible.
That said there are some issues with your code you should correct.
First: Do not import in a function. Instead write all your imports at the top of your code.
Second: I am not sure why you are doing .pack(in_=error_frame). This is not something one would ever really need. Just make sure that your label is already assigned to the correct frame. The in_ argument is rarely used and probably most people never use it. I have been on here for two years now and this is the first time I have seen anyone use that argument.
Third: You have not shown your imports for Tkinter however based on how you have written you code it looks like you have done:
import tkinter
from tkinter import *
This is overkill and is not a good idea. Just do import tkinter as tk and make sure you use tk. prefix where it applies.
Here is your code remade:
import tkinter.ttk as ttk
import tkinter as tk
from PIL import ImageTk, Image
def show_toplevel_window():
global im_error
window_linkedin = tk.Toplevel(root)
window_linkedin.geometry('1000x590')
frame = tk.Frame(window_linkedin)
frame.pack()
error_frame = tk.Frame(frame, highlightbackground="green", highlightcolor="green", highlightthickness=1)
error_frame.pack()
error_label = tk.Label(frame, font=("Helvetica Neue", 20), text="It appears there are no results for the selected country")
error_label.pack()
im_error = Image.open("./ressources/images_gui/aw_snap.png")
im_error = im_error.resize((500, 500), Image.ANTIALIAS)
im_error = ImageTk.PhotoImage(file = "./ressources/images_gui/aw_snap.png")
im_error_label = tk.Label(error_frame, image=im_error)
im_error_label.pack()
root = tk.Tk()
show_toplevel_window()
root.mainloop()

Unable to display image using tkinter [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 5 years ago.
I have the following code:
from tkinter import *
import os
from PIL import ImageTk, Image
#Python3 version of PIL is Pillow
class Scope:
def __init__(self, master):
self.master = master
f = Frame(root)
self.greet_button = Button(f, text="Back", command=self.back)
self.greet_button.pack(side= LEFT)
self.greet_button = Button(f, text="Detect", command=self.detect)
self.greet_button.pack(side= LEFT)
self.close_button = Button(f, text="Continue", command=master.quit)
self.close_button.pack(side=LEFT)
photo = PhotoImage(file='demo.gif')
cv = Label(master, image=photo)
cv.pack(side= BOTTOM)
f.pack()
def greet(self):
print("Previous image...")
root = Tk()
my_gui = Scope(root)
root.mainloop()
My first problem is that when I run this, all the buttons and the window show up, but there is no image. There is a square place holder indicating that the image should be in that box, but no image actually shows. I'm able to display the image if I just type the following:
root = Tk()
photo = PhotoImage(file='demo.gif')
label = Label(root, image=photo)
label.pack()
root.mainloop()
So, I know it's possible. But I don't know what I'm doing wrong with my GUI code. I've tried debugging this quite a bit and nothing seemed to work.
A second problem is, I am completely unable to display a jpg file in a GUI. I've tried using every tutorial and nothing quite does the trick. Ideally, I'd like to just be able to display a jpg image, if that's not possible, I'll settle for displaying a gif.
Your reference to photo gets destroyed / carbage collected by Python after the class is called, so, there is nothing the label could show.
In order to avoid this, you have to maintain a steady reference to it, i.e. by naming it self.photo:
from tkinter import *
import os
from PIL import ImageTk, Image
#Python3 version of PIL is Pillow
class Scope:
def __init__(self, master):
self.master = master
f = Frame(root)
self.greet_button = Button(f, text="Back") #, command=self.back)
self.greet_button.pack(side=LEFT)
self.greet_button = Button(f, text="Detect") #, command=self.detect)
self.greet_button.pack(side=LEFT)
self.close_button = Button(f, text="Continue", command=master.quit)
self.close_button.pack(side=LEFT)
self.photo = PhotoImage(file='demo.gif')
cv = Label(master, image=self.photo)
cv.pack(side=BOTTOM)
f.pack()
def greet(self):
print("Previous image...")
root = Tk()
my_gui = Scope(root)
root.mainloop()
PS: Your code snippet was not running properly because two functions were missing.

Categories