Reputation: 37
I am getting this error every time I run my code:
NameError: name 'pygame' is not defined
Here's my code:
from tkinter import *
from tkinter import filedialog
from pygame import mixer
from pygame.locals import *
class MusicPlayer:
def __init__(self, window ):
window.geometry('320x100'); window.title('MNote Player'); window.resizable(0,0)
Load = Button(window, text = 'Load', width = 10, font = ('Lucida Grande', 14), command = self.load)
Play = Button(window, text = 'Play', width = 10,font = ('Lucida Grande', 14), command = self.play)
Pause = Button(window,text = 'Pause', width = 10, font = ('Lucida Grande', 14), command = self.pause)
Stop = Button(window ,text = 'Stop', width = 10, font = ('Lucida Grande', 14), command = self.stop)
Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
self.music_file = False
self.playing_state = False
def load(self):
self.music_file = filedialog.askopenfilename()
def play(self):
if self.music_file:
pygame.mixer.init()
pygame.mixer.music.load(self.music_file)
pygame.mixer.music.play()
def pause(self):
if not self.playing_state:
pygame.mixer.music.pause()
self.playing_state=True
else:
pygame.mixer.music.unpause()
self.playing_state = False
def stop(self):
pygame.mixer.music.stop()
root = Tk()
app= MusicPlayer(root)
root.mainloop()
I have no other .py
file called pygame
, and I have checked many similar problems, and I cannot find an answer.. I am only a beginner, so please don't go to harsh on me!
Upvotes: 1
Views: 1406
Reputation: 478
you do not actually import pygame
please add import pygame
to use the whole module. When you use from pygame import mixer
and from pygame.locals import *
you are importing submodules if they have a __init__
inside or just plain classes or files if they do not include __init__
.
Importing pygame by itself imports the pygame module so that you can call it and activate that __init__
or call submodules.
Upvotes: 0
Reputation: 546083
You are not importing pygame
. You are, however, importing pygame.mixer
. So use that directly in your code (mixer.init()
etc. instead of pygame.mixer.init()
).
Alternatively, change the import directive from
from pygame import mixer
to
import pygame.mixer
Upvotes: 3