Play sound effect when you press a Button in Tkinter - python

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.

Related

When I open new window with button click, also another mini window pops up

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 to use user input to display image?

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
----------------------------------------

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.

Not Able to See the Picture in Tkinter Python Program

topper = Toplevel()
topper.title("2nd Window")
topper.state('zoomed')
my_img = ImageTk.PhotoImage(Image.open("diamond.png"))
my_label = Label(topper, image=my_img, height = 100 , width = 100)
F21 = Frame(topper, borderwidth=83, bg="blue", relief=SUNKEN)
button1 = Button(topper, text="class", command=topper.destroy)
button1.pack()
my_label.pack()
I am running the code and I get no errors, button is working as well but I'm not able to see the picture in the window.
Welcome to Stackoverflow Shakti!
For the future - it is always good to supply a Minimal, Reproducible Example so others can replicate and understand your issue better in order to help you! It also helps you to understand where exactly the error originates.
When you call Toplevel() from another tkinter window to open a new window, you will need to call "mainloop()" on the second window as well in order to display an image - try my code with an example image and comment/uncomment the line with
topper.mainloop()
to see the difference in functionality.
The adapted code:
from tkinter import *
from PIL import Image, ImageTk # pip install pillow
def show_second_window():
topper = Toplevel()
topper.title("2nd Window")
topper.state('zoomed')
my_img = ImageTk.PhotoImage(Image.open("t1.png"))
my_label = Label(topper, image=my_img, height=100, width=100)
F21 = Frame(topper, borderwidth=83, bg="blue", relief=SUNKEN)
button1 = Button(topper, text="class", command=topper.destroy)
button1.pack()
my_label.pack()
topper.mainloop() # <---- this is needed to show the image!
root = Tk()
root.title("1st window")
button = Button(root, text="show second window", command=show_second_window)
button.pack()
root.mainloop()

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")

Categories

Resources