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.
Related
I want to open new window with button click and close the old one. I tried to do that with this code, but when I click button it's also open another mini window with title 'tk'. How can I prevent that?
from tkinter import *
from PIL import Image, ImageTk
def openOperationsGui():
window.destroy()
operationsWindow = Toplevel()
operationsWindow.title("Operations")
operationsWindow.geometry("1366x768")
window = Tk()
logo = Image.open("resources\logo.png")
logoImg = ImageTk.PhotoImage(logo)
logoLbl = Label(image=logoImg)
logoLbl.place(x=450, y=120, height=500, width=500)
conn = Button(window, text="Connect", fg='blue', command=openOperationsGui)
conn.place(x=450, y=533, height=87, width=490)
passw = Entry(window, text="", bd=5)
passw.place(x=620, y=480, height=50, width=150)
window.title('Title')
window.geometry("1366x768")
window.mainloop()
How do I use user input to retrieve an image, and display it on the screen? I have the user input field in Tkinter, and I do not know how to get that to go to my folder, and get the image to show up on the same screen.
EDIT: I was able to get the path to show on the screen, but now I don't know how to get the actual image to show up from that path inside the frame... I do not know how to link this path to have the program display the image, i.e. myimage1 from my folder.
from tkinter import *
from PIL import ImageTk,Image
from tkinter import ttk
from tkinter import filedialog
root = Tk()
root.title("Images")
root.iconbitmap(r'C:\Users\hadhikari\example\Takumi_Logo.ico')
button_quit = Button(root, text= "Exit Program", command=root.quit)
button_quit.pack()
e= Entry(root, width=50, bg="light blue", borderwidth=3)
e.pack()
e.insert(0," ")
def myClick():
link = "r'C:\\Users\\hadhikari\\example\\" + e.get()
myLabel1 = Label(root, text=link)
myLabel1.pack()
myButton = Button(root, text="Scan Part Number", command=myClick,
bg="pink", fg="white")
myButton.pack()
#my_img = ImageTk.PhotoImage(Image.open('link'))
#my_Label = Label(image=my_img)
#my_Label.pack()
#def getText():
# inputtedtext = entrybox.get()
#entrybox = Entry(root)
#entrybox.pack()
#btn = Button(root, text="Submit", command=getText)
#btn.pack()
frame = LabelFrame(root, padx=100, pady=100)
frame.pack(padx=50, pady=50)
root.mainloop()
As suggested in the comments, maybe using Tkinter's askopenfilename dialog might be a better choice than hardcoding the filepath, and letting the user input the filename.
But, first of all, let's fix the code following your intentions. Most of the part on how to properly set up a Tkinter Label, and dynamically place images in that, can be easily found, for example in this Q&A. Basically, you want to put the "update routine" inside your myClick method:
from tkinter import *
from PIL import Image, ImageTk
# How to properly set up Tkinter label with dynamically changeable
# ImageTk.PhotoImage: https://stackoverflow.com/a/3482156/11089932
root = Tk()
button_quit = Button(root, text='Exit Program', command=root.quit)
button_quit.pack()
e = Entry(root, width=50, bg='light blue', borderwidth=3)
e.pack()
e.insert(0, '')
my_label = Label()
my_label.pack()
def myClick():
link = r'your/path/goes/here' + e.get()
my_img = ImageTk.PhotoImage(Image.open(link))
my_label.configure(image=my_img)
my_label.image = my_img
myButton = Button(root, text='Scan Part Number', command=myClick,
bg='pink', fg='white')
myButton.pack()
root.mainloop()
Program at startup:
Opening the first image:
Opening another image:
Now, regarding the askopenfilename dialog, we get rid of the Entry widget, and simply open the dialog inside the myClick method:
from tkinter import *
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk
# How to properly set up Tkinter label with dynamically changeable
# ImageTk.PhotoImage: https://stackoverflow.com/a/3482156/11089932
root = Tk()
button_quit = Button(root, text='Exit Program', command=root.quit)
button_quit.pack()
my_label = Label()
my_label.pack()
def myClick():
link = askopenfilename()
my_img = ImageTk.PhotoImage(Image.open(link))
my_label.configure(image=my_img)
my_label.image = my_img
myButton = Button(root, text='Scan Part Number', command=myClick,
bg='pink', fg='white')
myButton.pack()
root.mainloop()
Program at startup:
Opening the first image (dialog):
Opening the first image (display):
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.19041-SP0
Python: 3.9.1
PyCharm: 2021.1.3
Pillow: 8.3.1
----------------------------------------
When trying to place an image in a button, I get an error "_tkinter.TclError: image "pyimage1" doesn't exist". The image does exist though because I used it on another button and it works there.
When I try to use the image again on a second button that's when the error occurs.
I have tried removing the image and the button works. Tried using the image on anther button and it works for one button only.
from tkinter import ttk
from tkinter import Tk, PhotoImage
class Window(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
def main():
root = Tk()
style = ttk.Style(root)
style.theme_use('clam')
root2 = Tk()
style = ttk.Style(root2)
style.theme_use('alt')
root3 = Tk()
style = ttk.Style(root3)
style.theme_use('classic')
root4 = Window()
style = ttk.Style(root4)
style.theme_use('default')
icon = PhotoImage(file='test.gif')
# This line works, the image appears on the button.
ttk.Button(root, image=icon, compound='left', text="Quit", command=root.destroy).pack()
# This line works with out the image.
ttk.Button(root2, compound='left', text="Quit", command=root2.destroy).pack()
# This line does not work with an image.
# if the line below is un-commented the code does not work, the error I get is below.
# _tkinter.TclError: image "pyimage1" doesn't exist
# ttk.Button(root2, image=icon, compound='left', text="Quit", command=root2.destroy).pack()
ttk.Button(root3, text="Quit", command=root3.destroy).pack()
ttk.Button(root4, text="Quit", command=root4.destroy).pack()
root.mainloop()
if __name__ == '__main__':
main()
I want images on all buttons.
I can only get it to work for one button only.
You're going to have to create another PhotoImage for each window with the master keyword:
icon = PhotoImage(master=root, file='test.gif')
icon2 = PhotoImage(master=root2, file='test.gif')
icon3 = PhotoImage(master=root3, file='test.gif')
icon4 = PhotoImage(master=root4, file='test.gif')
And then use each icon for the corresponding button:
ttk.Button(root, image=icon, compound='left', text='Quit', command=root.destroy).pack()
ttk.Button(root2, image=icon2, text='Quit', command=root2.destroy).pack()
ttk.Button(root3, image=icon3, text='Quit', command=root3.destroy).pack()
ttk.Button(root4, image=icon4, text='Quit', command=root4.destroy).pack()
Hope this works for you.
How do I create an image in button. Instead of having text saying "Draw" I want it to be a picture of a brush.
Code:
self.draw_button = Button(self.root, text='Draw', command=self.use_draw)
self.draw_button.grid(row=0, column=2)
Create an image with tkinter's PhotoImage then set it inside Button.
from tkinter import *
root = Tk()
img = PhotoImage(file='paint_brush.png')
draw_button = Button(root, image=img)
draw_button.grid(row=0, column=0)
root.mainloop()
How can I get sound effects when I press buttons on the GUI for Tkinter?
Here is my code:
from Tkinter import *
root = Tk() #root object for the buttons
from PIL import Image, ImageTk #python imaging library
#open the images and store them in photos
image = Image.open("Jolteon.PNG")
image1 = Image.open("Eevee.PNG")
image2 = Image.open("Vaporeon.PNG")
image3 = Image.open("Flareon.PNG")
photo = ImageTk.PhotoImage(image)
photo1 = ImageTk.PhotoImage(image1)
photo2 = ImageTk.PhotoImage(image2)
photo3 = ImageTk.PhotoImage(image3)
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root) #some different frames
bottomFrame.pack(side=BOTTOM)
button1 = Button(topFrame, text="Eevee", fg="brown")
button2 = Button(topFrame, text="Jolteon", fg="yellow")
button3 = Button(topFrame, text="Vaporeon", fg="blue")
button4 = Button(topFrame, text="Flareon", fg="red")
button5 = Button(topFrame,image=photo)
button6 = Button(topFrame,image=photo1)
button7 = Button(topFrame,image=photo2) #sdbsdfbdfsbdfb
button8 = Button(topFrame,image=photo3)
#packages the buttons so that it can be produced
button1.pack()
button6.pack()
button2.pack() #sdbsdbsdbsdfbfdsn
button5.pack()
button3.pack()
button7.pack()
button4.pack()
button8.pack()
root.mainloop()
It displays names and pictures of the Eevee trios from Pokemon.
What I want is when I press the picture of the pokemon to make the pokemon cry.
How would I go on about implementing this?
You have to link the click of your mouse on the image, with an even handler (or simply method):
btn = tkinter.Button(root, text='Play Sound', width=16, bg='#2ff')
btn.bind('<Button-1>', on_click)
# binding the click of btn with the on_click function
btn.pack()
# note the parameter 'event', since this is a even handler
def on_click(event):
# play music
You could use the pygame module, and specifically you could use its mixer module for playing music. You could easily install the pygame module for your version of Python and for Windows from the official website.
Once the installation is finished, you have first to initialise the Pygame modules with this command pygame.init(). Remember to uninitialize the same modules once you stop using them with the command pygame.quit(). Note that you can initialise single modules, like the mixer module, which is the exact one that you should use.