Displaying .jpg image when button is clicked in Tkinter? - python

This seems like a pretty straightforward question, but i am having trouble displaying a jpg image when a button is clicked. Here is my code (without the button code for the sake of time):
from tkinter import *
#screen stuff here
canvas = Canvas(app)
canvas.grid(row = 0,column = 0)
photo = PhotoImage(file = "test.jpg")
canvas.create_image(0,0, image = photo)
def show_image():
global canvas
global photo
canvas.create_image(0,0, image = photo)
#button that calls the function down here
Thanks!

This works with Python2:
import Tkinter as tk
import ImageTk
def show_image():
x = canvas.create_image(125, 125, image=tk_img)
while True:
print('show')
canvas.itemconfigure(x, state=tk.NORMAL)
button.configure(text = 'Hide')
yield
print('hide')
canvas.itemconfigure(x, state=tk.HIDDEN)
button.configure(text = 'Show')
yield
root = tk.Tk()
canvas = tk.Canvas(root, width=250, height=250)
canvas.grid(row=0, column=0)
tk_img = ImageTk.PhotoImage(file='image.png')
button = tk.Button(
root, text="Show", command=show_image().next, anchor='w',
width=10, activebackground="#33B5E5")
button.grid(row=1, column=0)
root.mainloop()
In Python3, PhotoImage can open GIF, PPM/PGM images. To open other formats, you may need to install Pillow (a fork of the PIL project for Python3).

Related

How can I manage to put a button image into an image background Tkinter

Good day everyone, can I ask how can I manage to put this button inside an image background
code:
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title("Japanese Retro Hub")
root.geometry('2200x1000')
#Image
bg = Image.open("RetroHub_BG_Main.png")
resized = bg.resize((2200,1000), Image.ANTIALIAS)
bg = ImageTk.PhotoImage(resized)
bglabel = Label(root, image=bg)
bglabel.pack(pady=20)
#text for my_command and Start exit button
text = Label(root, text= "Hello world")
text.pack(pady=30)
def my_command():
text.config(text="You have clicked Me...")
def start_exit_button():
click_btn = PhotoImage(file='start_button.png')
img_label= Label(image=click_btn)
button = Button(root, image=click_btn,command=my_command,borderwidth=0)
button.pack(padx=50, pady=20)
root.mainloop()
start_exit_button()
root.mainloop()
This is the image example that I am trying to portray
https://drive.google.com/file/d/1VzbhNazEnfOCk0_QZOD_nWR5jsb-a8GB/view?usp=sharing

python3 tkinter GUI with clickable transparent images

I have made a background for my GUI in inkscape and have managed to add a transparent image over the top to use as buttons but cant figure out how to make them run a subroutine (nav) when clicked. I either need an image with transparency over the top of my background that I can click or a completely see through rectangle that I can position over a button drawn on the background image in inkscape. I'm on Ubuntu if it matters.
from tkinter import *
from PIL import ImageTk, Image
import sys
root = Tk ()
root.title('GUI')
root.geometry("1000x564")
root.attributes('-zoomed', True)
root.attributes("-type", "splash")
#define image
bg = ImageTk.PhotoImage(file="BACKGROUND.png")
#create canvas
my_canvas = Canvas(root, width=800, height=500)
my_canvas.pack(fill="both", expand=True)
my_canvas.create_image(0,0, image=bg, anchor = NW)
def nav():
print ("navigation")
#creating button which supports png transparency
#button = PhotoImage(file="button2.png")
#my_canvas.create_image(260,-70, anchor=NW, image=button, state='normal', )
buttonImage = ImageTk.PhotoImage(Image.open("button.png"))
button = my_canvas.create_image(50, 50, image=buttonImage)
my_canvas.tag_bind(Button, "<Button-1>", nav())
def resizer(e):
global bg1, resized_bg, new_bg
# open image
bg1 = Image.open("BACKGROUND.png")
# resize
resized_bg =bg1.resize((e.width, e.height), Image.ANTIALIAS)
#DEFINE IMAGE AGAIN
new_bg =ImageTk.PhotoImage(resized_bg)
#add back to the canvas
my_canvas.create_image(0,0, image=new_bg, anchor = NW)
# my_canvas.create_image(260,-70, anchor=NW, image=button, state='normal', )
button = my_canvas.create_image(50, 50, image=buttonImage)
def close(e):
root.destroy()
root.bind('<Configure>', resizer)
root.bind('<Escape>', close)
root.mainloop()
when calling function with my_canvas.tag_bind(button, "<Button-1>", nav) nav(root) is actually being called when clicked so def nav(root): has to be used for the sub routine to run correctly.

Displaying image on Tkinter button click

I'm building an app that's supposed to display various images from a local folder depending on which button is clicked in the app.
So far, I have started out with an example I've found and try to modify it, but I can't figure out how to summon a .jpg or .png via a button click in the first place. Here's my very basic code so far:
import tkinter as tk
def write_slogan():
print("Tkinter is easy to use!")
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)
root.mainloop()
Essentially, instead of writing the slogan in the console, I would like the button click to trigger an image being displayed. How would I go about achieving that?
I have amended your code so when you click your button the image "test.png" will display on a label.
Here is the code for testing, in my case "test.png" was in the same directory as my Python script.
import tkinter as tk
render = None
def write_slogan():
# get image and display
image = tk.PhotoImage(file = "test.png")
imageLabel.configure(image = image)
imageLabel.image = image
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)
imageLabel = tk.Label(frame)
imageLabel.pack(side=tk.LEFT)
root.mainloop()
Also, this thread was helpful.
You can pass the image filename to the function, so that different buttons show different images:
import tkinter as tk
from PIL import ImageTk
def show_image(imagefile):
image = ImageTk.PhotoImage(file=imagefile)
imagebox.config(image=image)
imagebox.image = image # save a reference of the image to avoid garbage collection
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame, text="QUIT", fg="red", command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame, text="Hello", command=lambda: show_image("slogan.png"))
slogan.pack(side=tk.LEFT)
other = tk.Button(frame, text="World", command=lambda: show_image("other.jpg"))
other.pack(side=tk.LEFT)
# label to show the image
imagebox = tk.Label(root)
imagebox.pack()
root.mainloop()
Since tk.PhotoImage() does not support JPG image, external Pillow module is used instead.

How do I switch images before clicking a button in Python using TKinter

In the following code, I want to display picture1.jpg as soon as button1 is pressed. After some time, I want to display picture2.jpg. In the following case, only picture2.jpg is displayed 5 seconds after the button1 is pressed. How can I change pictures?
from Tkinter import *
from PIL import Image, ImageTk
import time
def show_image():
while True:
image = Image.open("picture1.jpg")
tk_img = ImageTk.PhotoImage(image)
x = canvas.create_image(400, 300, image=tk_img)
canvas.itemconfigure(x, state=NORMAL)
# I want to show picture1.jpg now
time.sleep(5) #This is a dummy because it takes a while for picture2.jpg
#Now I can show picture2.jpg
image = Image.open("picture2.jpg")
tk_img = ImageTk.PhotoImage(image)
x = canvas.create_image(400, 300, image=tk_img)
canvas.itemconfigure(x, state=NORMAL)
yield
root = Tk()
canvas = Canvas(root, width=850, height=750)
canvas.grid(row=0, column=0)
button1 = Button(
root, text="Insert next device and then take a picture", command=show_image().next, anchor='w',
width=50, activebackground="#33B5E5" ,fg = "blue" , font=("Arial", 24))
button1.grid(row=1, column=0)
root.mainloop()
First, as a general rule you should never call sleep in the main thread of a GUI. It causes your whole program to pause -- buttons won't work, the screen won't update, etc.
Tkinter has a way to run code in the future. Change the image, and then use this function to change it back later. Roughly speaking, it would look like this:
def show_image(path):
image = Image.open(path)
tk_img = ImageTk.PhotoImage(image)
x = canvas.create_image(400, 300, image=tk_img)
def switch_images():
show_image("picture1.jpg")
root.after(5000, show_image, "picture2.jpg")

Simple Image viewer

I am new to this site, and I am trying to create a simple image viewer in Python 2.7 using Tkinter, But when I try to load an image in it,it does not show anything!, I bet it is something embarassingly obvious, but I dont know what's wrong. I am using Windows XP. Here's my code:
from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image
root = Tk(className="Image viewer")
canvas_width = 800
canvas_height = 600
root.config(bg="white")
def openimage():
picfile = tkFileDialog.askopenfilename()
img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=img)
yscrollbar = Scrollbar(root)
yscrollbar.pack(side=RIGHT, fill=Y)
xscrollbar = Scrollbar(root, orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X)
canvas = Canvas(root, width=canvas_width, height=canvas_height, yscrollcommand=yscrollbar.set, xscrollcommand=xscrollbar.set)
button = Button(root,text="Open",command=openimage)
button.pack(side=BOTTOM)
canvas.pack(side=TOP)
yscrollbar.config(command=canvas.yview)
xscrollbar.config(command=canvas.xview)
mainloop()
Update: It works when i remove the file browser, and give it the path to a file, but i want the file browser, and using a label works, but scroll bars dont work with it, and i want to be able to scroll the picture.
I found on "The Tkinter PhotoImage Class" that PhotoImage can't be assigned to local variable in function because garbage collector remove it.
So you can use global variable:
img = None
def openimage():
global img
picfile = tkFileDialog.askopenfilename()
img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=img)
or assign image to existing widget (for example canvas)
def openimage():
picfile = tkFileDialog.askopenfilename()
canvas.img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=canvas.img)
by the way: you should check if file was selected
def openimage():
picfile = tkFileDialog.askopenfilename()
if picfile:
canvas.img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=canvas.img)
add scrollregion and you have file viewer with working scrollbars
def openimage():
picfile = tkFileDialog.askopenfilename()
if picfile:
canvas.img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=canvas.img)
canvas.configure(canvas, scrollregion=(0,0,canvas.img.width(),canvas.img.height()))
Dont know about problem in your code but You can use this function in place of your one:
def openimage():
try:
Artwork.destroy()
except Exception:
pass
picfile = tkFileDialog.askopenfilename()
img = ImageTk.PhotoImage(file=picfile)
#canvas.create_image(0,0, anchor=NW, image=img)
Artwork=Label(root,image=img)
Artwork.img=img
Artwork.pack(side=BOTTOM)#do packing urself
Note that is is the minimal implementation.

Categories

Resources