Reputation: 5
I want a file to open on a button press within my tkinter gui. However, the sound file plays when my program runs (as in straight away) and doesn't work when the button is pressed. Here is my code:
####Imports
import os
import sys
from tkinter import *
####definitions
def blackobj ():
from os import startfile
startfile ('simon_objection.mp3')
####Window
mGui = Tk()
mGui.geometry ('1280x720+100+50')
mGui.title ('Gui App')
mGui.configure(background='blue')
####Labels
#Title
wlabel = Label(text = "Welcome to the Ace Attorney Soundboard!", font = 'georgia',fg ='white', bg = 'blue').place(x=0,y=0)
objectionheader = Label (text = 'Objections:', font = 'georgia', fg = 'white', bg = 'blue',).place (x=0,y=45)
####Buttons
objblackquill = Button (mGui, text = 'Blackquill', font = 'georgia', command =blackobj()).place (x=0,y=75)
mGui.mainloop()
Have I made a mistake in my code or do I need to add something else to get the sound to work when the button is pressed and not when the script runs?
Thanks
Upvotes: 0
Views: 193
Reputation:
objblackquill = Button (mGui, text = 'Blackquill', font = 'georgia', command =blackobj()).place (x=0,y=75)
Your problem is with the above line. When Python reads your code, it sees blackobj()
, which it interprets as a valid function call. So, it executes it.
To fix the problem, you could use a lambda
to "hide" the call to blackobj
inside a function of its own:
objblackquill = Button (..., command=lambda: blackobj()).place (x=0,y=75)
However, since you are not passing blackobj
any arguments, an even better solution is to just remove the parenthesis:
objblackquill = Button (..., command=blackobj).place (x=0,y=75)
Also, tkinter.<widget>.place
always returns None
and therefore should be called on its own line.
In other words, every line written like this:
wlabel = Label(...).place(x=0,y=0)
should be written like this instead:
wlabel = Label(...)
wlabel.place(x=0,y=0)
Upvotes: 3