Tkinter buttons with images not appearing - python

So, i was trying to make a music player with python and tkinter and I had to set images for the buttons, but when I set an image for the button, the button does not appear on the output screen
Code:
from tkinter import *
import pygame
win = Tk()
win.title("Music player")
win.geometry("500x300")
# Images for buttons
back_png = PhotoImage("C:/1 Files and Folders/SHARAN/Python/SVE atom/Images/back.png")
back_button = Button(win, image=back_png, borderwidth=0).place(x=100, y=20)
win.mainloop()

tkinter requires a keyword for most arguments. Here you are missing the file= keyword.
back_png = PhotoImage(file="C:/1 Files and Folders/SHARAN/Python/SVE atom/Images/back.png")

Related

Click to select new image for button - not working

I am trying to create a function for multiple buttons that allows the user to click on a specific button and change the associated image. For now I'm trying to change the image of a single button, but the image doesn't seem to be loaded or recognized for some reason. Any ideas?
import tkinter as tk
from tkinter import simpledialog,filedialog,colorchooser,messagebox,Frame,Button
from PIL import ImageTk, Image
def img_mod():
global btn
ret = filedialog.askopenfilename()
loadn = Image.open(ret)
root.render2 = ImageTk.PhotoImage(loadn)
btn['image'] = loadn
root = tk.Tk()
load1 = Image.open("example.jpg")
root.render1 = ImageTk.PhotoImage(load1)
btn = tk.Button(root, text="My Button", image = root.render1)
btn['command'] = img_mod
btn.pack(fill='both', expand=True)
root.mainloop()
You can run this Python code if you save it with an image titled "example.jpg" in the same folder.

How to make a file open by default with tkinter app?

I made a tkinter app for displaying images, and I was wondering if there's a way to make an image open by default with this app
At the moment if I try that, I get an error for some non declared icon file (this is the icon that appears near the name of the app at the top)
There's no real goal behin this Gui, I'm just experimenting and learning.
Thanks
Try this:
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
my_img = []
def FileImport():
file = filedialog.askopenfilename()
my_img.clear()
my_img.append(ImageTk.PhotoImage(Image.open(file)))
label1.config(image=my_img[0])
root= tk.Tk()
root.title('Main')
root.geometry('400x400')
label = tk.Label(root, text = "Browse", fg="purple")
label.pack()
button = tk.Button(root, text='See Image',fg="blue", command=FileImport)
button.pack()
my_img.append(ImageTk.PhotoImage(Image.open(your_first_image)))
label1 = tk.Label(root, image = my_img[0])
label1.pack(pady= 50)
root.mainloop()
When you run this:
After you tap to see different image from computer:
Hope It helps!

Sounds in Python (tkinter) [duplicate]

I am building a program for Windows PCs that contains a lot of buttons and seems very plain. So I was wondering, can I make it so when you push a button (using tkinter), can I play a sound to liven up the program a bit? Please keep in mind I am learning so please dumb it down a bit.
Assuming your file is a WAV:
from tkinter import *
from winsound import *
root = Tk() # create tkinter window
play = lambda: PlaySound('Sound.wav', SND_FILENAME)
button = Button(root, text = 'Play', command = play)
button.pack()
root.mainloop()
Assuming your file is a MP3:
from Tkinter import *
import mp3play
root = Tk() # create tkinter window
f = mp3play.load('Sound.mp3'); play = lambda: f.play()
button = Button(root, text = 'Play', command = play)
button.pack()
root.mainloop()
You might want to consider using pygame as a cross-platform alternative to winsound.
import tkinter as tk
from pygame import mixer
mixer.init()
sound = mixer.Sound("sound.ogg")
root = tk.Tk()
tk.Button(root, command=sound.play).pack()
root.mainloop()
Refer to the docs for more information.
You first need to link the click of your mouse on the image, with an even handler, then simply define an on_click function:
def on_click(event):
winsound.Beep('frequency', 'duration')
Here you can find more information about playing sounds in python.
Just use
import os
os.system("play sound.mp3")

Initalize Tkinter inside a class or method?

Is it possible to put all of my code to initalize my tKinter or pygame display into its own class, just to tidy things up. Its all code that gets executed once before I get into my main loop?
Im writing something that uses both a pygame graphic display and a tKinter frame for a GUI. It all works fine, but it seems so messy having all this with no indents right in my main line of code. Nothing clever, just reading the monitor resolution, then using that to adjust the size and location of my PyGame and Tkinter frames.
Ive edited code below to show my main loops, and how i update tkinter and pygame displays. It all works OK.
I just wonder if i could tidy things up by using a class to hold all the buttins etc that i want on the tkinter display.
Wish I could put it all in a class or something. Sorry, i'm a noob, having a blast playing with python!
import random
import math
import os
import pygame
import numpy as np
#from tkinter import *
#from tkinter import ttk
from tkinter import Tk, Button, Label, LabelFrame, PhotoImage, Radiobutton
from tkinter import messagebox, DISABLED, NORMAL, Menu
pygame.init()
infoObject = pygame.display.Info() #Read video mode full resolution
pygame.display.set_mode((infoObject.current_w, infoObject.current_h)) #Intialize pygame window to full screen mius 400 on left (to be used for tkinter main window)
SMALL_TEXT = pygame.font.Font('freesansbold.ttf', 12)
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 30) #set placement for next window in windows env
gameDisplay = pygame.display.set_mode((infoObject.current_w - 400,infoObject.current_h - 70), pygame.RESIZABLE)
pygame.display.set_caption('Collision Detection')
pygame.font.init() # Set up text ops
root = Tk()
geom = (str(400) + 'x' + str(infoObject.current_h - 70) + '+' + str(infoObject.current_w - 410) + '+' + str(0))
root.geometry(geom)
root.configure(background='gray70')
root.title('Vessel Control')
# Create a couple test buttons and labels on root form, to be updated by code in mainloop
lab = Label(root, text="Don't Push The Button!")
lab.grid(row=0, column=0)
but = Button(root, text="Push Me", command=changebut)
but.grid(row=1, column=0)
posxlab = Label(root, text='USV X Position (m): ')
posxlab.grid(row=2, column=0)
# Here i set up the rest of the junk for my program
# Then i start my own main loop, not usuing tkinters.
# Main loop
while not gameExit:
#And my full code is in here, a few thousand lines or so
pygame.display.update() #update pygame display
root.update_idletasks() #process tkinter events
root.update() #Update tkinter window
clock.tick(FRAME_RATE)
pygame.quit()
quit()

Python tkinter Button not responding

TKINTER GRAPHICS
from tkinter import *
tk = Tk()
btn = Button(tk, text="Click Me") #Makes a useless button
btn.pack() #Shows the button
import turtle #Makes the graphics work
t = turtle.Pen()
def hello(): #Makes button not
print('hello here')
btn = Button(tk, text="Click Me", command=hello)
The program SHOULD say hello there when I click the button, but I can't click the button because it won't respond.
As noted in the comments, you appear to create the same button twice, once where it's not connected to a function but packed, and once where it's connected to a function but not packed. If you combine the two, you'll get a working button.
But let's jump in and fix another problem before it begins -- you invoked:
t = turtle.Pen()
No, not when you're working within tkinter. If you're working with turtle standalone, it's Turtle/Pen and Screen, but if you're working within tkinter, it's RawTurtle/RawPen and TurtleScreen. Otherwise you end up with extra windows and potential root conflicts.
Combining all the above together, adding a scrolled canvas for the turtle to play on, and changing the print() to the console to be a turtle.write() to the scrolled canvas, we get:
import tkinter as tk
import turtle # Makes the graphics work
def hello(): # Makes button not
turtle.write('hello there', align='center', font=('Arial', 18, 'normal'))
root = tk.Tk()
button = tk.Button(root, text="Click Me", command=hello) # Makes a button
button.pack() # Shows the button
canvas = turtle.ScrolledCanvas(root)
canvas.pack(side=tk.LEFT)
screen = turtle.TurtleScreen(canvas)
turtle = turtle.RawPen(screen, visible=False)
screen.mainloop()

Categories