'NameError: name 'player' is not defined - but it was defined, just in another function
The below code gives an error, "NameError: name 'player' is not defined". I dont understand why. When I have the music just playing, without needing to be triggered by the Play button; then the Pause button works. But the moment when I put the command to start playing music within a function, the pause button stops working, and gives the error: "NameError: name 'player' is not defined"
import vlc
import time
import pafy
from tkinter import *
url = "https://www.youtube.com/watch?v=yV25KhUH1BE"
win = Tk()
pause = 0
def func():
global pause
pause = -(pause-1)
player.set_pause(pause)
def func2():
video = pafy.new(url)
best = video.getbestaudio()
playurl = best.url
instance = vlc.Instance()
player = instance.media_player_new()
media=instance.media_new(playurl)
media.get_mrl()
player.set_media(media)
player.play()
btn = Button(win,
text = "Pause",
command = func)
btn.pack()
btn2 = Button(win,
text = "play",
command = func2)
btn2.pack()
win.mainloop()
The code above is just a trial, not the full project.
Solution 1:[1]
So as far as I understand, the error is coming from
def func():
global pause
pause = -(pause-1)
player.set_pause(pause)
This might be because "player" isn't actually defined.
In func2, you have defined player = instance.media_player_new()
so it's doesn't throw any error.
In "func", you missed it.
I think that is causing an issue. Try defining "player" globally. That might help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ayushman Kumar |